我怎么写这个只有一次点击数据库呢?

时间:2015-05-18 19:31:45

标签: php mysql laravel eloquent fluent

这就是我目前所拥有的:

$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();
}

1 个答案:

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