0

在前端表单中,我有多个文件上传字段。所以在提交表单时,我在数据库中创建了一个新记录,然后尝试将多个图像附加到它,如下所示:

模型类中指定的画廊的关系

public $attachMany = [
    'gallery' => 'System\Models\File',
];

前端表单处理

function onCreate() {
    $data = post();
    
    $newRecord = Record::create($data);
    
    if (Input::hasFile('gallery')) {
        $newRecord->gallery()->create(['data' => Input::file('file_input')]);
    }
}

前端表单 HTML

<form method="POST" accept-charset="UTF-8"
      data-request="onCreate" data-request-files data-request-flash>

    <input accept="image/*" name="gallery" type="file" id="gallery" multiple>

</form>

但是,我不断收到以下错误:

SQLSTATE [HY000]:一般错误:1364 字段“磁盘名称”没有默认值

设置$guarded = []vendor/october/rain/src/Database/Attach/File.php没有帮助。

4

1 回答 1

1

您需要array file field name gallery[], 发布多个文件并在 PHP 端接收它们。

// html changes 
<input accept="image/*" name="gallery[]" type="file" id="gallery" multiple>
//                      HERE       --^ make it array for multiple files 


// PHP side
// $newRecord = ...your code;
if (Input::hasFile('gallery')) {
    foreach(Input::file('gallery') as $file) {

        $fileModel = new System\Models\File;
        $fileModel->data = $file;
        $fileModel->is_public = true;
        // $fileModel->save(); <- save only if you are adding new file to existing record
        // other wise let differ binding handle this 
       
        $newRecord->gallery()->add($fileModel); 
    }     
}
// $newRecord->save();   

它应该可以解决您的问题。

如有任何疑问,请发表评论。

于 2020-10-18T18:31:24.027 回答