使用 eloquent 从 laravel 中的 select 插入

Md.*_*ain 1 php mysql laravel eloquent laravel-8

我正在使用 laravel 8。我想通过从一个表选择到另一个表来插入多行。我正在使用 DB::statement() 但现在想使用 eloquent 来做到这一点。这是我的示例代码:

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); 
Run Code Online (Sandbox Code Playgroud)

我怎样才能使用单个雄辩命令来做到这一点?另外,laravel 中还有其他更智能/更快的方法吗?

Ste*_*lov 5

我不知道有什么 Eloquent 方法可以做到这一点,但是在 Laravel 5.7.17 之后,我们在查询构建器 insertUsing() 中有一个新方法。不幸的是,官方文档中没有提到这一点。

查询生成器代码将如下所示:

$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);
Run Code Online (Sandbox Code Playgroud)

已测试并工作。请记住,您不要使用 ->get() 运行选择请求。