简体   繁体   中英

insert multiple rows using join in a table

I want to insert multiple rows in a table from different tables using join by a single query.When I run the below query it shows error

$insert=DB::table('tableA')->insert(DB::raw('SELECT ss.col1,ts.col2,ts.col3,ts.col4,ts.col5,
                5 AS col6 FROM 
                tableB AS ts
                 INNER JOIN tableC AS t ON ts.col2=t.id 
                 INNER JOIN tableD AS ss 
                 ON ts.col1=ss.col1 
                 AND ts.col3=ss.col3
                 AND ts.col4=ss.col4 
                 AND ts.col5=ss.col5
                 INNER JOIN tableE AS s 
                 ON ss.col1=s.id
                 WHERE t.status=1
                 AND s.status=1'));

Error:Argument 1 passed to Illuminate\\Database\\Query\\Builder::insert() must be of the type array, object given.

actually it return object where as insert method expects array. I used raw query it inserts the data but timestamp doesn't populate and it doesn't return the inserted rows count as well.

how can I get both using laravel query builder ??

Try this. It will work if columns in tableA have the same names as in your select:

$insert=DB::table('tableA')
->insert(json_decode(json_encode(DB::select('SELECT ss.col1,ts.col2,ts.col3,ts.col4,ts.col5,
                5 AS col6 FROM 
                tableB AS ts
                 INNER JOIN tableC AS t ON ts.col2=t.id 
                 INNER JOIN tableD AS ss 
                 ON ts.col1=ss.col1 
                 AND ts.col3=ss.col3
                 AND ts.col4=ss.col4 
                 AND ts.col5=ss.col5
                 INNER JOIN tableE AS s 
                 ON ss.col1=s.id
                 WHERE t.status=1
                 AND s.status=1')),true));

First you can store the result of the first query in a variable:

$data = DB::select('SELECT ss.col1,ts.col2,ts.col3,ts.col4,ts.col5,
    5 AS col6 FROM 
    tableB AS ts
    INNER JOIN tableC AS t ON ts.col2=t.id 
    INNER JOIN tableD AS ss 
    ON ts.col1=ss.col1 
    AND ts.col3=ss.col3
    AND ts.col4=ss.col4 
    AND ts.col5=ss.col5
    INNER JOIN tableE AS s 
    ON ss.col1=s.id
    WHERE t.status=1
    AND s.status=1');

Then convert the data to array:

$data = collect($data)->map(function($x){ return (array) $x; })->toArray();

And finally insert it into DB, supposing the columns match.

$insert = DB::table('tableA')->insert($data);

EDIT

You can use this code to push the values for timestamps fields, supposing this two fields are ate the end of the table's specification, ensuring the columns match with values:

$data = collect($data)->map(function($x){ 
    return array_push((array) $x, date('Y-m-d H:i:s'), date('Y-m-d H:i:s'));
})->toArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM