这就是我目前所拥有的:
$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();
}
答案 0 :(得分:2)
如果您想要单个语句进行更新,则需要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);