如何将多个更新传递给Laravel中的不同记录?

问题描述 投票:1回答:2

Laravel允许插入多行作为要插入的数组行数组

https://laravel.com/docs/5.5/queries#inserts

DB::table('users')->insert([
    ['email' => '[email protected]', 'votes' => 0],
    ['email' => '[email protected]', 'votes' => 0] 
]);

有没有替代做同样的更新?

DB::table('users')->update[
    [update to record 1],
    [update to record 2]
];
laravel laravel-5 laravel-5.5
2个回答
0
投票

您可能需要使用newQuery方法

$rows = [
    [id => '1', 'email' => 'foo@bar'], 
    [/*...*/]
];

$query = DB::table('users');

foreach(var $i=0; $i<count($rows); $i++) {

    if($i > 0) {
        $query->newQuery();
    }

    $query->where('id', $rows[$i]['id'])
          ->update(['email' => $rows[$i]['email'];

}

这可能有效(未经测试)


0
投票

您可以使用特定查询,如以下示例所示。

假设我们有这样的结构:

+----+----------+-------------+---------+
| id | username | club        | country |
+----+----------+-------------+---------+
|  2 | Messi    | Barca       | Arg     |
|  3 | Ronaldo  | Juventus    | Por     |
|  4 | Salah    | Liverpool   | Egy     |
+----+----------+-------------+---------+

我们希望在一个查询中更新所有行和列。

我们可以使用以下说明:

 $table = 'players';// table name

 // values to update
 $values = [['id' => '2','club' =>'Barca',  'country' => 'Argentina'],
            ['id' => '3','club' =>'Man Utd','country' => 'Portugal'],
            ['id' => '4','club' =>'Chelsea','country' => 'Egypte']];


 $cases = [];
 $ids = [];
 $param1 = []; // for the first column
 $param2 = []; // for the Seconde column
 $params = []; // for merging all columns

 foreach ($values as $value) {

     $value=(object)$value;
     $id = (int) $value->id;
     $cases[] = "WHEN {$id} then ?";
     $param1[] =$value->club;
     $param2[] =$value->country;
     $ids[] = $id;
 }

 $params=array_merge($param1,$param2);

 $ids = implode(',', $ids);
 $cases = implode(' ', $cases);    

\DB::update("UPDATE `{$table}` 
             SET `club`    = CASE `id` {$cases} END ,
                 `country` = CASE `id` {$cases} END 
             WHERE `id` in ({$ids})", $params);

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.