需要一些帮助将以下Laravel Eloquent for循环查询转换为单个MySQL查询,该查询一次性访问数据库 . 基本上,这将根据$ cardQueryList中的项目数量多次命中数据库 .
for($i=0; $i<count($cardQueryList); $i++) {
$userCard = Collection::firstOrNew( ['username' => $cardQueryList[$i]['username'], 'card_uid' => $cardQueryList[$i]['card_uid']] );
$userCard->have_quantity = $cardQueryList[$i]['have_quantity'];
$userCard->save();
}
这就是我目前拥有的:
DB::raw('REPLACE INTO users_collection (username, card_uid, have_quantity) values('.$cardQueryList[$i]["username"].', '.$cardQueryList[$i]["card_uid"].', '.$cardQueryList[$i]["have_quantity"].')');
问题是我使用'username'和'card_uid'作为唯一键来查找要更新的相应行 . 另一个问题是,这需要我为所有字段指定所有值,否则字段将丢失或替换为默认值 .
如何将原始MySQL查询命中一次,而不是像Laravel Eloquent代码中那样n次?或者有没有办法用Eloquent打一次数据库(这将是最好的,但我不认为有办法)?
2 回答
edit 根据您的评论,您可以使用
DB
进行批量更新,使用以下内容:原始SQL真的是你正在寻找的,或者你可以简单地做这些事情:
这就是我解决它的方式 .