一次更新多行 Laravel Eloquent

Update multiple rows at once Laravel Eloquent

我的 table products 具有以下结构。

id | name | promote

其中promote列是boolean类型。

我想将 boolean 列的值设置为选定行的 1 并将 0 设置为非选定行。我在控制器中有以下代码来处理这个查询。

$yes = Tour::whereIn('id', $request->promote)->get();
$no = Tour::whereNotIn('id', $request->promote)->get();

foreach ($yes as $item) {
    $item->promote = 1;
    $item->save();
}

foreach ($no as $item) {
    $item->promote = 0;
    $item->save();
}

我从表单请求中得到关注。

上面的代码确实有效,但我认为它不是很有效。我正在寻找以更有效的方式实现结果的可选方法。

取回结果,循环遍历,可以直接更新,

$yes =  Tour::whereIn('id', $request->promote)->update(['promote' => 1]);
$no =  Tour::whereNotIn('id', $request->promote)->update(['promote' => 0]);

如果您不关心通过模型进行更新,您可以调用生成器上的更新来更新所有匹配的记录。由于这将使用构建器而不是模型,因此不会触发任何模型事件:

// set them all to promote = 0
Tour::update(['promote' => 0]);
// or  just set the ones that need to be 0
Tour::whereNotIn('id', $request->promote)->update(['promote' => 0]);

// set the ones you want to promote = 1
Tour::whereIn('id', $request->promote)->update(['promote' => 1]);

只是一种尝试的方法。