我想执行多个更新语句而不是单独执行它们以避免多次DB命中。以下是代码
$updateStatement = '';
foreach ($users as $user) {
$i++;
$updateStatement = $updateStatement. "update users set packet_seqno = '".$i."' where id = ".$user->id . '; ';
}
\DB::statement($updateStatement);
然而,它不起作用并抛出错误
SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在'update
附近使用正确的语法
你能帮我解决这个问题吗?
这是$ 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; "
答案 0 :(得分:1)
如果你想使用雄辩,你可以这样做:
foreach ($users as $user) {
$i++;
User::where('id',$user->id)->update(['packet_seqno' => $i]);
}
或更好:
foreach ($users as $user) {
$i++;
$user->update(['packet_seqno' => $i]);
}
答案 1 :(得分:0)
试试这个:
$updateStatement = '';
foreach ($users as $user) {
$i++;
$updateStatement = "update users set packet_seqno = '".$i."' where id = ".$user->id;
\DB::update(\DB::raw($updateStatement));
}
看,如果有帮助。