如何在 Laravel5 中插入数组字段数据
How to insert array fields data in Laravel5
如何使用 Laravel 插入多个文本字段数据。
我有两个字段。
<input type="text" name="title[]" />
<input type="text" name="email[]" />
现在在控制器中我可以获得如下这些值。
$name = $request->title;
$description = $request->email;
这是我打印这些值时得到的结果。
Array
(
[0] => title1
[1] => title2
)
Array
(
[0] => desc1
[1] => desc2
)
如何使用 eloquent 添加这个。
方法一:
$name = $request->title;
$description = $request->email;
if(count($name) > count($description))
$count = count($description);
else $count = count($name);
for($i = 0; $i < $count; $i++){
$objModel = new ModelName();
$objModel->name = $name[$i];
$objModel->description = $description[$i];
$objModel->save();
}
方法二:
$name = $request->title;
$description = $request->email;
if(count($name) > count($description))
$count = count($description);
else $count = count($name);
for($i = 0; $i < $count; $i++){
$data = array(
'name' => $name[$i],
'description' => $description[$i]
);
$insertData[] = $data;
}
ModelName::insert($insertData);
如何使用 Laravel 插入多个文本字段数据。 我有两个字段。
<input type="text" name="title[]" />
<input type="text" name="email[]" />
现在在控制器中我可以获得如下这些值。
$name = $request->title;
$description = $request->email;
这是我打印这些值时得到的结果。
Array
(
[0] => title1
[1] => title2
)
Array
(
[0] => desc1
[1] => desc2
)
如何使用 eloquent 添加这个。
方法一:
$name = $request->title;
$description = $request->email;
if(count($name) > count($description))
$count = count($description);
else $count = count($name);
for($i = 0; $i < $count; $i++){
$objModel = new ModelName();
$objModel->name = $name[$i];
$objModel->description = $description[$i];
$objModel->save();
}
方法二:
$name = $request->title;
$description = $request->email;
if(count($name) > count($description))
$count = count($description);
else $count = count($name);
for($i = 0; $i < $count; $i++){
$data = array(
'name' => $name[$i],
'description' => $description[$i]
);
$insertData[] = $data;
}
ModelName::insert($insertData);