假设我们有一个数据库,其中有一个名为fathers的表;另一个表叫做children。
我要所有父亲是妈妈的孩子。
$pls = children::where(['father_id' => 5, 'isGoodBoy' => true])->take(4)->get();
And i want change$pls设置"father_id"为"7
,8
,50
,55
"。所以可以在foreach:
for ($i = 0; $i < count($pls); $i++) {
$pls[$i] = $arayWhoWantBaby[$i];
$pls[$i]->save();
}
这项工作,但做了许多要求…(在本例中,1个get请求和4个更新请求!)
我想用一个或两个DB请求做到这一点,一个从DB获取数据,另一个用一个请求设置新数据来完成所有工作和更新项$pls[0][1][2]…
一件事是"in"SQL中的关键字;
这就是我的意思。老实说,我只会坚持额外的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);