通过 eloquent 更新 laravel 中的多行

update multi rows in laravel by eloquent

假设我们有一个数据库,其中有一个 table 叫做 fathers;另一个 table 叫做 children.

我要得到所有 children 父亲是 mamali 的人。

$pls = children::where(['father_id' => 5, 'isGoodBoy' => true])->take(4)->get(); 

我想更改 $pls 并将 father_id 设置为 7,8,50,55.所以可以在 foreach 中一个一个地执行此操作:

for ($i = 0; $i < count($pls); $i++) {
    $pls[$i] = $arayWhoWantBaby[$i];
    $pls[$i]->save();
}

这项工作但需要处理很多请求...(在本例中有 1 个获取请求和 4 个更新请求!)

我想通过一个或两个数据库请求执行此操作,一个从数据库获取数据,另一个设置新数据,一个请求完成所有工作并更新项目 $pls[0][1][2].. .

sql 中的“in”关键字用于更新;

这就是我的意思。老实说,我只会坚持额外的 4 个查询。像这样的小更新应该不是问题。

此外,这样做不会触发任何 Eloquent 事件。

$father_ids = [7, 8, 50, 55];
$children_ids = children::where(['father_id' => 5, 'isGoodBoy' => true])->take(4)->pluck('id')->all();

$sql = <<<SQL
UPDATE
    children
SET
    father_id = CASE id
        WHEN :children_id_1 THEN :father_id_1
        WHEN :children_id_2 THEN :father_id_2
        WHEN :children_id_3 THEN :father_id_3
        WHEN :children_id_4 THEN :father_id_4
    END
WHERE
    id IN (:children_id_1, :children_id_2, :children_id_3, :children_id_4)
SQL;

$bindings = [
    'children_id_1' => $children_ids[0],
    'children_id_2' => $children_ids[1],
    'children_id_3' => $children_ids[2],
    'children_id_4' => $children_ids[3],
    'father_id_1' => $father_ids[0],
    'father_id_2' => $father_ids[1],
    'father_id_3' => $father_ids[2],
    'father_id_4' => $father_ids[3],
];

DB::update($sql, $bindings);