问题描述
在前端表单中,我有多个文件上传字段。因此,在提交表单时,我在数据库中创建了一条新记录,然后尝试将多个图像附加到该记录,如下所示:
在模型类中指定的图库的关系
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>
但是,我不断遇到以下错误:
在$guarded = []
中设置vendor/october/rain/src/Database/Attach/File.PHP
并没有帮助。
解决方法
您需要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();
它应该可以解决您的问题。
如有任何疑问,请发表评论。