1

I am using laravel 8. I want to insert multiple rows by selecting from one table to another. I am using DB::statement() but now want to do it using eloquent. Here is my sample code:

DB::statement("insert into bank_information (user_id, bank_id, account_name,account_number)
        select applicant_id,bank_id,account_name,account_number from applicant_bank_information
        where erec_applicant_bank_information.applicant_id =".$applicant_id); 

How can I do it using single eloquent command ? Also, Is there any other smarter/faster way for it in laravel ??

0

1 Answer 1

6

I do not know of a Eloquent way for this, but after Laravel 5.7.17 we have a new method in the query builder insertUsing(). Unfortunately this is not mentioned in the official documentation.

The query builder code will be something like this:

$select = DB::table('applicant_bank_information as abi')
    ->select('applicant_id','bank_id','account_name','account_number')
    ->where('abi.applicant_id', $applicant_id);
    
$rows_inserted = DB::table('bank_information')
    ->insertUsing(['user_id','bank_id', 'account_name','account_number'], $select);

Tested and working. Keep in mind that you do not run the select request with ->get().

Sign up to request clarification or add additional context in comments.

1 Comment

Note that every column in the target table has to be accounted for, including primary keys. This may involve doing like ->selectRaw('null as id')->addSelect(...) on the source query.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.