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 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决