我正在尝试插入多个行--表中有外键,但它不起作用。
表尺寸
id -> PK AI
| size_name
| size_price
表库存
id->PK AI
pid-> FK
size_id ->FK (表号)
qty
我的控制器看起来是这样的:
控制器
$sizes = new sizes;
foreach($request->size as $key => $value)
{
$size[] = [
'size_name' => $request->size[$key],
'pid' => $lastid,
'size_price' => $request->sizeprice[$key],
'created_at' => Carbon::now(),
];
}
DB::table('sizes')->insert($size);
$lastidsize = $sizes->id;
$stocks = new stocks;
foreach($request->stock as $key => $value)
{
$stock[] = [
'pid' => $lastid,
'size_id' => $lastidsize,
'qty' => $request->stock[$key],
'created_at' => Carbon::now(),
];
}
DB::table('stocks')->insert($stock);误差
**Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'size_id' cannot be null (SQL: insert
into `stocks` (`created_at`, `pid`, `qty`, `size_id`) values (2021-01-24 11:40:50, 91, 1, ?), (2021-
01-24 11:40:50, 91, 1, ?), (2021-01-24 11:40:50, 91, 1, ?))**请帮帮忙
发布于 2021-01-24 23:00:21
$sizes没有身份证。您可以使用此函数:
DB::table('sizes')->insertGetId($size);另外,请查看这些链接以获得更多帮助:https://www.nicesnippets.com/blog/laravel-insertgetid-multiple-rows-example
https://stackoverflow.com/questions/65870104
复制相似问题