我在 Laravel 5.5 上有一个学生表单,用户可以在其中添加尽可能多的爱好。每个爱好都有标题、描述和图像。我想保存所有爱好
。我怎样才能保存这些信息?
我的看法
<form action="/" method="post" enctype="multipart/form-data" files="true">
<input name="feat[]" type="text" placeholder="Feat 1">
<textarea name="feat_desc[]" placeholder="Feat 1 Desc">
<input type="file" name="feat_img[]">
<input name="feat2" type="text" placeholder="Feat 2">
<textarea name="feat2desc" placeholder="Feat 2 Desc">
<input type="file" name="feat2img">
<button>Add New Hobby</button>
用于动态字段的 JQuery
$('#add-form').click(function() {
i++;
$('#add-me').append(
'<input id="quantity" type="text" name="feat[]">'
'<textarea name="feat_desc[]">'
'<input type="file" name="feat_img[]">'
);
});
我的 Controller :
public function create($Request $requst, Student $student)
$posts = Student::create([
'name' => request('name'),
'interests' => request('interests'),
'hobbies' => json_encode(request('hobbies')),
]);
return redirect ('/');
我的数据库迁移
{
Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('interests');
$table->text('hobbies');
$table->timestamps();
});
}
最佳答案
更新答案: 我强烈建议你将每个爱好记录在一个单独的表中,因为这样更清晰,也更有利于搜索和索引。您可能有第二个表爱好,如下所示:
Schema::create('student_hobbies', function (Blueprint $table) {
$table->increments('id');
$table->integer('student_id')->unsigned();
$table->string('title');
$table->text('description');
$table->string('path');
$table->timestamps();
});
然后将每个爱好及其学生 ID 保存在新记录中。在这种情况下,您还可以将图像保存到数据库中,而不是将它们保存在单独的存储中。请参阅this thread了解更多信息。
无论如何如果您决定将所有这些信息放在一个字段中,请执行以下操作:
首先,循环请求,将文件以唯一的名称保存到合适的位置,并结合你的爱好 然后使用json_encode将爱好保存到数据库:
public function create($Request $requst, Student $student)
$hobbies = [];
$images = $request->file('feat_img');
$descriptions = $request->feat_desc;
foreach ($request->feat as $key => $title) {
$filename = '';
if (!empty($files[$key]) && $files[$key]->isValid()) {
$filename = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
$files[$key]->move(storage_path('images'), $filename);
}
$hobbies[] = [
'title' => $title,
'desc' => $description[$key],
'image' => $filename,
];
}
$posts = Student::create([
'name' => request('name'),
'interests' => request('interests'),
'hobbies' => json_encode($hobbies),
]);
}
上一个答案: 您可以使用 CSV 或 JSON 编码形式将多个数据保存到单个列:
public function create($Request $requst, Student $student)
$posts = Student::create([
'name' => request('name'),
'interests' => request('interests'),
'hobbies' => json_encode(request('hobbies')), // implode(',', request('hobbies'))
]);
return redirect ('/');
在 HTML 中,爱好应如下所示:
<input name="hobbies[]" />
<input name="hobbies[]" />
...
关于php - Laravel - 将多个数据保存到数据库中的一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47102608/