Mysql 如何在Laravel中插入多个ID不同的行
我需要一种方法将多行插入到sql表中,并使用一个sql查询返回所有插入的不同主键IDMysql 如何在Laravel中插入多个ID不同的行,mysql,laravel,Mysql,Laravel,我需要一种方法将多行插入到sql表中,并使用一个sql查询返回所有插入的不同主键ID foreach($request->size as $key => $value) { $size = new sizes; $size->size_name = $request->size[$key]; $size->size_price = $request->sizeprice[$key]; $size->pid = $last_
foreach($request->size as $key => $value)
{
$size = new sizes;
$size->size_name = $request->size[$key];
$size->size_price = $request->sizeprice[$key];
$size->pid = $last_id;
$size->save();
$size_last_id = $size->id;
}
foreach($request->stock as $key => $value)
{
$stock = new stocks;
$stock->pid = $last_id;
$stock->size_id = $size_last_id;
$stock->stock_qty = $request->stock[$key];
$stock->save();
}
请查找此图像的附件。
当您使用foreach循环插入数据时,上述代码将只返回最后插入的行的id
最好将所有id存储在一个数组中,将变量声明为数组并将id推送到数组中
示例代码。
$size_last_id = [];
foreach($request->size as $key => $value)
{
$size = new sizes;
$size->size_name = $request->size[$key];
$size->size_price = $request->sizeprice[$key];
$size->pid = $last_id;
$size->save();
array_push($size_last_id, $size->id);
}
这将把所有插入的ID存储到数组中
希望这会有用。谢谢。我正试图将数组保存到数据库中,但出现了“数组到字符串转换”错误
$size_last_id = [];
foreach($request->size as $key => $value)
{
$size = new sizes;
$size->size_name = $request->size[$key];
$size->size_price = $request->sizeprice[$key];
$size->pid = $last_id;
$size->save();
array_push($size_last_id, $size->id);
}