Laravel SQL 更新行 WHERE IN 分组依据



我这里有一个小问题。与其在 for 循环中运行 10 个查询,我不想在一个查询上执行此操作。

我的代码目前如下所示:

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

所以,我不想在一个查询上做这件事,而不是为5000个用户运行相同的查询,这将非常慢地完成......

我尝试做这样的事情:

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

$games数组如下所示:

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

但它只通过数组中的第一个值更新 10 行。
如何使数组中每game_id仅更新一行?

我理解你想要实现的目标,并承担了自己的挑战。下面的代码经过测试,可以执行您想要的操作。它获取列表中每个游戏的第一个未分配给任何用户的免费连续剧。第二个查询将选定的序列分配给用户。

$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]);

您可以在不使用循环的情况下执行此操作。您可以在条件中传递游戏数组。请尝试下面给出的代码-

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

最新更新