dongpo5239 2017-05-18 10:51
浏览 124
已采纳

Laravel SQL更新行由WHERE IN Group By

I have a little problem here. Instead of running 10 queries inside for loop, I wan't to do it on one query.

My code looks like this at the moment:

foreach($games as $game_id){
    DB::table('game_serials')
    ->whereNull('user_id')
    ->where('game_id', $game_id)
    ->update([
        'user_id' => 1
    ]);
}

So, I wan't to do it on one query instead of running this same for lets say 5000 users, which would be extremely slow to finish...

I have tried to do something like this:

DB::table('game_serials')
->whereNull('user_id')
->whereIn('game_id', $games)
->groupBy('game_id')
->limit(10)
->update([
    'user_id'    => 1
]);

$games array looks like this:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)

But it only updates 10 rows by first value from array.
How can I make it to update only one row per game_id in array?

  • 写回答

2条回答 默认 最新

  • donglianglu8136 2017-05-18 13:01
    关注

    I understand what you're trying to achieve and took it upon myself to do this as a challenge. The below code is tested and does what you desire. It fetches the first free serial that isn't assigned to any user for each game in the list. The second query assigns the selected serials to the user.

    $serials = DB::table('game_serials')
        ->selectRaw('min(id) as id')
        ->whereNull('user_id')
        ->whereIn('game_id', $games)
        ->groupBy('game_id')
        ->get()
        ->pluck('id');
    
    $result =  DB::table('game_serials')
        ->whereIn('id', $serials)
        ->update(['user_id' => 1]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号