简体   繁体   English

Laravel 5 用不同的值更新多行

[英]Laravel 5 update multiple rows with different values

I have been searching everywhere for a solution to this, I hope someone has already solved it or has some good ideas for improvement.我一直在到处寻找解决方案,我希望有人已经解决了它或者有一些改进的好主意。

I am using Laravel 5 and I have come accross a situation where I need to update many rows with new values.我正在使用 Laravel 5,我遇到了需要用新值更新许多行的情况。 Right now I'm doing a for-loop for all those rows to update them and I would like to optimize this so that I don't run many sql queries.现在我正在为所有这些行做一个 for 循环来更新它们,我想优化它,这样我就不会运行很多 sql 查询。 Here's an example code:这是一个示例代码:

<?php

   //Well, the original code looks better than this, but the concept is the same

   $myrows = [0,1,2,3,4,5,6,7,8,9];
   $myvalues = [45,543,657,574,234,26457,2462,897,234,89032];

   for($i=0;$i<count($myrows);$i++) {
      MyClass::where('id', $myrows[$i])->update(['myColumn' => $myvalues[$i]]);
   }

?>

Obviously this will execute 10 queries (the same amount as the rows I want to update), but I want to do this with only one query, for optimization purposes.显然,这将执行 10 个查询(与我要更新的行数相同),但出于优化目的,我只想用一个查询来执行此操作。 I am aware of the ability to update many rows at the same time with whereIn(...)->update(...) but with this method you can only update all rows to the same value, not different ones like in my example.我知道可以使用 whereIn(...)->update(...) 同时更新多行,但是使用这种方法,您只能将所有行更新为相同的值,而不是像我的例如。

Thanks in advance for any help !在此先感谢您的帮助!

$myRows = [0,1,2,3,4,5,6,7,8,9];
$myValues = [45,543,657,574,234,26457,2462,897,234,89032];

if (empty($myRows)) {
    // return or throw exception
    return;
}
if (count($myRows) != count($myValues) {
    // in case of dynamic values for $myRows/$myValues
    return;
}
$cases = [];
$cases[] = "CASE id";

for ($myRows as $row) {
    $cases[] = "WHEN {$row} THEN ?";  
}

$cases = implode(" ", $cases);
$ids = implode(",", $myRows);

DB::update("UPDATE `my_table` SET `my_column` = {$cases} END WHERE `id` in ({$ids})", $myValues);

in SQL every single query is executing in sequence.在 SQL 中,每个查询都按顺序执行。

foreach ( array_combine($myrows,$myvalues) a $id => $val){
          MyClass::find($val)->update(['myColumn' => $val]);
}

only thing you can do is to append queries, and send it once, something like this:您唯一能做的就是附加查询,然后发送一次,如下所示:

$builder = DB::table((new MyClass)->getTable());
$sql='';

foreach ( array_combine($myrows,$myvalues) a $id => $val){
          $sql .= $builder->getGrammar()->insert($builder->where('id', $id),['myColumn' => $val]);
}
DB::connection()->getPdo()->prepare($sql)->execute();

It's not the matter of Laravel QueryBuilder.这不是 Laravel QueryBuilder 的问题。 If you could do your stuff in one SQL query only, you almost could do it with Laravel.如果你只能在一个 SQL 查询中完成你的工作,你几乎可以用 Laravel 来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM