I am trying to do insert multiple rows there are foreign keys in a table but it is not working.
Table Sizes
| id -> PK AI
| size_name
| size_price
Table Stocks
| id->PK AI
| pid-> FK
| size_id ->FK (Table size)
| qty
my controller looks like this:
Controller
$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);
Error
**IlluminateDatabaseQueryException
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, ?))**
help please
question from:
https://stackoverflow.com/questions/65870104/laravel-multiple-records-at-once-for-single-foreign-key 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…