【问题标题】:How can I write this so it only hits the database once?我怎样才能写这个,所以它只命中数据库一次?
【发布时间】:2015-05-18 19:31:45
【问题描述】:

这是我目前拥有的:

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

【问题讨论】:

    标签: php mysql laravel eloquent fluent


    【解决方案1】:

    如果你想更新单个语句,你需要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);
    

    【讨论】:

      猜你喜欢
      • 2020-11-28
      • 2021-04-25
      • 2021-07-26
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 2021-08-09
      • 1970-01-01
      相关资源
      最近更新 更多