我怎样才能写这个让它只访问数据库一次?
How can I write this so it only hits the database once?
这是我目前拥有的:
$sortOrder = ['0','1','4','2','3'];
$cards = ComboCard::where('username', '=', $user->username)
->where('combo_uid', '=', $comboUid)
->select('id', 'card_order')
->orderBy('card_order', 'ASC')
->get();
for($i=0; $i<count($cards); $i++) { // currently hits the database n times based on count($cards)
$index = $sortOrder[$i];
$cards[$index]->card_order = $i;
$cards[$index]->save();
}
如果要单语句更新,需要case
.
就是说,您不会使用 Eloquent,而是使用原始连接 update
(假设该数组中的值为 card_order
- 我会改用 ids
):
$cases = $bindings = [];
foreach ($sortOrder as $new => $previous) {
$cases[] = 'when ? then ?';
$bindings[] = $previous;
$bindings[] = $new;
}
// placeholders for the where in clause: ?,?,?,?,...
$placeholders = implode(',', array_fill(0, count($sortOrder), '?'));
// bindings for the where in clause
$bindings = array_merge($bindings, $sortOrder);
$sql = 'update `cards` set `card_order` = case `card_order` '.implode(' ', $cases).' end'.
' where `card_order` in ('.$placeholders.')';
DB::update($sql, $bindings);
这是我目前拥有的:
$sortOrder = ['0','1','4','2','3'];
$cards = ComboCard::where('username', '=', $user->username)
->where('combo_uid', '=', $comboUid)
->select('id', 'card_order')
->orderBy('card_order', 'ASC')
->get();
for($i=0; $i<count($cards); $i++) { // currently hits the database n times based on count($cards)
$index = $sortOrder[$i];
$cards[$index]->card_order = $i;
$cards[$index]->save();
}
如果要单语句更新,需要case
.
就是说,您不会使用 Eloquent,而是使用原始连接 update
(假设该数组中的值为 card_order
- 我会改用 ids
):
$cases = $bindings = [];
foreach ($sortOrder as $new => $previous) {
$cases[] = 'when ? then ?';
$bindings[] = $previous;
$bindings[] = $new;
}
// placeholders for the where in clause: ?,?,?,?,...
$placeholders = implode(',', array_fill(0, count($sortOrder), '?'));
// bindings for the where in clause
$bindings = array_merge($bindings, $sortOrder);
$sql = 'update `cards` set `card_order` = case `card_order` '.implode(' ', $cases).' end'.
' where `card_order` in ('.$placeholders.')';
DB::update($sql, $bindings);