php - 我该如何编写它,使其只访问数据库一次?

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

最佳答案

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

关于php - 我该如何编写它,使其只访问数据库一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30311416/

相关文章:

php - 从 php 文件到 phpmyadmin 的数据库连接失败?

javascript - 复选框顺序不正确

php - Laravel 处理异常

MYSQL 数据库查询与连接和计数

mysql - 无法通过套接字 'var run mysqld mysqld.sock 在 Ubuntu 上连接到 mysql 服务器 (Emma)

php - Laravel Cashier Mollie 事件监听器未触发事件

laravel - 多个站点使用 1 个代码库,最好的设置是能够一次更新所有站点的核心问题,但每个站点都有自己的自定义设置?

php - 比较两个字符串并返回不匹配的子字符串

php - 使用表单 php>form>php 传递变量时出错

PHP preg_match : a pattern which satisfies all MySQL field names (including 'table.field' formations)