这个问题与Eloquent save() method not working inside for loop有关。
过程图:上传文件>创建默认值0的表行>继续迭代0个部分(例如,如果最后一个3-> 4,5,6)
在第一个图像上传过程之后,我想继续将图像添加到特定项目。
$ input ['id']:保存项目ID值。
我确实像这样应用each()方法:
*** code part executed after multiple file upload ***
TABLE STATUS AT FIRST STAGE :
+---------+-------------+-----------+
| id | project_id | order_id |
+---------+-------------+-----------+
| 1 | 15 | 1 |
+---------+-------------+-----------+
| 2 | 15 | 2 |
+---------+-------------+-----------+
| 3 | 16 | 1 | --> Added in the past
+---------+-------------+-----------+
| 4 | 16 | 0 | --> Created on first stage** : default 0.
+---------+-------------+-----------+
| 5 | 16 | 0 | --> Created on first stage** : default 0.
+---------+-------------+-----------+
*** code continues ***
$start = Images::select('order_id')->where('project_id', '=', $input['id'])
->orderBy('order_id', 'DESC')->first();
Images::where('project_id', '=', $input['id'])->where('order_id', '=', 0)->get()
->each(function($ord) use (&$start) {
$ord->order_id = $start++;
$ord->save();
});
执行上面给出的代码后表格结果(仍在处理中)
+---------+-------------+-----------+
| id | project_id | order_id |
+---------+-------------+-----------+
| 1 | 15 | 1 |
+---------+-------------+-----------+
| 2 | 15 | 2 |
+---------+-------------+-----------+
| 3 | 16 | 1 | --> Added in the past
+---------+-------------+-----------+
| 4 | 16 | 0 | --> New / Present Action : 1st file
+---------+-------------+-----------+
| 5 | 16 | 0 | --> New / Present Action : 2nd one
+---------+-------------+-----------+
期望:
+---------+-------------+-----------+
| id | project_id | order_id |
+---------+-------------+-----------+
| 1 | 15 | 1 |
+---------+-------------+-----------+
| 2 | 15 | 2 |
+---------+-------------+-----------+
| 3 | 16 | 1 | --> Added in the past
+---------+-------------+-----------+
| 4 | 16 | 2 | --> New / Present Action : 1st file
+---------+-------------+-----------+
| 5 | 16 | 3 | --> New / Present Action : 2nd one
+---------+-------------+-----------+
出什么问题了?逻辑错误或each()错误?我不知道,但是我尝试过foreach,但我得到了同样错误的结果。任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
$start = Images::select('order_id')->where('project_id', '=', $input['id'])
->orderBy('order_id', 'DESC')->first();
返回Images
$ start-> order_id应包含您的ID号
答案 1 :(得分:0)
尝试在递增时访问id属性。
Images::where('project_id', '=', $input['id'])->where('order_id', '=', 0)->get()
->each(function($ord) use (&$start) {
$ord->order_id = $start->id++;
$ord->save();
});