如何使用Laravel Eloquent从数组应用值并更新行?

时间:2015-05-18 09:37:15

标签: php mysql laravel eloquent

如果我有这样的表:

+--------+-------------------+-----------+
| ID     | Type              |  nOrder   |
+--------+-------------------+-----------+
| 1      | A                 | 0         |
| 2      | A                 | 1         |
| 3      | A                 | 2         |
| 4      | B                 | 0         |
| 5      | B                 | 1         |
| 6      | B                 | 2         |
| 7      | B                 | 3         |
| 8      | B                 | 4         |
| 9      | C                 | 0         |
| 10     | C                 | 1         |
+--------+-------------------+-----------+

使用Laravel Eloquent:

$sortOrder = [1, 2, 0, 3, 4];

$list = Type::where('Type', '=', 'B')
    ->orderBy('nOrder', 'ASC')
    ->update(['nOrder' => ??? ]); // how can i apply the $sortOrder values at ???

我的猜测是,更新看起来像这样:

->update(['nOrder' => $sortOrder[DB::raw('`nOrder`')] ]); // this doesn't work though

预期结果如下:

+--------+-------------------+-----------+
| ID     | Type              |  nOrder   |
+--------+-------------------+-----------+
| 1      | A                 | 0         |
| 2      | A                 | 1         |
| 3      | A                 | 2         |
| 4      | B                 | 1         |
| 5      | B                 | 2         |
| 6      | B                 | 0         |
| 7      | B                 | 3         |
| 8      | B                 | 4         |
| 9      | C                 | 0         |
| 10     | C                 | 1         |
+--------+-------------------+-----------+

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法......

$sortOrder = [1, 2, 0, 3, 4];
$updateArray = ['Type' => 'B', 'param2' => ''];
$collection = Type::whereIn('nOrder', $sortOrder);
$data = $collection->get();
$collection->update($updateArray);

我没有对此进行测试,但这应该可行。