简体   繁体   English

Laravel 5.0批量更新

[英]Laravel 5.0 bulk update

I would like to execute multiple update statements rather than executing them individually in order to avoid multiple DB hits.Following is the code 我想执行多个更新语句,而不是单独执行它们,以避免多个数据库命中。以下是代码

$updateStatement = '';
    foreach ($users as $user) {
        $i++;
        $updateStatement = $updateStatement. "update users set packet_seqno = '".$i."' where id = ".$user->id . ';  ';      
    }
    \DB::statement($updateStatement);

However, it is not working and throwing error 但是,它不起作用并引发错误

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update 检查与您的MySQL服务器版本相对应的手册,以获取在'update附近使用的正确语法

Can you please help me to fix this? 你能帮我解决这个问题吗?

Here is the dump of the $updateStatement. 这是$ updateStatement的转储。

"update ppt_import_mortgage1 set packet_seqno = '1' where id = 37;  update ppt_import_mortgage1 set packet_seqno = '2' where id = 39;  update ppt_import_mortgage1 set packet_seqno = '3' where id = 40;  update ppt_import_mortgage1 set packet_seqno = '4' where id = 42;  update ppt_import_mortgage1 set packet_seqno = '5' where id = 43;  update ppt_import_mortgage1 set packet_seqno = '6' where id = 44;  update ppt_import_mortgage1 set packet_seqno = '7' where id = 45;  update ppt_import_mortgage1 set packet_seqno = '8' where id = 46;  update ppt_import_mortgage1 set packet_seqno = '9' where id = 47;  update ppt_import_mortgage1 set packet_seqno = '10' where id = 48;  "

If you wish to use eloquent, you could simply do this: 如果您想使用口才,可以简单地做到这一点:

foreach ($users as $user) {
       $i++;
    User::where('id',$user->id)->update(['packet_seqno' => $i]);
}

or better: 或更好:

foreach ($users as $user) {
       $i++;
    $user->update(['packet_seqno' => $i]);
}

Try this: 尝试这个:

$updateStatement = '';
   foreach ($users as $user) {
       $i++;
       $updateStatement = "update users set packet_seqno = '".$i."' where id = ".$user->id; 
    \DB::update(\DB::raw($updateStatement));     
}

See, if that helps. 看,如果有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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