Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

php - Laravel multiple records at once for single foreign key

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$sizes has no id. You can use this function:

DB::table('sizes')->insertGetId($size);

also checkout these links for more help: https://www.nicesnippets.com/blog/laravel-insertgetid-multiple-rows-example

Laravel - multi-insert rows and retrieve ids


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...