我怎么写这个,使它只击中数据库一次


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);