我有一个如下所示的表,该表将用于项目图像。
id:主键
project_id:与项目相关的列。
order_num:表示特定项目的图像列表顺序(例如,项目的内部视图,建筑项目的外部视图,其他方面等)
+---------+-------------+-----------+
| id | project_id | order_num |
+---------+-------------+-----------+
| 1 | 15 | 0 |
+---------+-------------+-----------+
| 2 | 15 | 0 |
+---------+-------------+-----------+
| 3 | 16 | 0 |
+---------+-------------+-----------+
| 4 | 16 | 0 |
+---------+-------------+-----------+
| 5 | 16 | 0 |
+---------+-------------+-----------+
.
.
.
GOES ON LIKE THIS
What i want to do:
+---------+-------------+-----------+
| id | project_id | order_num |
+---------+-------------+-----------+
| 1 | 15 | 1 |
+---------+-------------+-----------+
| 2 | 15 | 2 |
+---------+-------------+-----------+
| 3 | 16 | 1 |
+---------+-------------+-----------+
| 4 | 16 | 2 |
+---------+-------------+-----------+
| 5 | 16 | 3 |
+---------+-------------+-----------+
我使用 苗条雄辩
我发现类似这样的内容,但是save()方法出现错误的方法错误。
$find = Images::where('project_id', '=', $project->id)->count();
$img = Images::where('project_id', '=', $project->id);
for ($i = 1; $i <= $find; $i++) {
$img->order_num = $i;
$img->save();
}
我做错什么了吗?任何帮助将不胜感激。
更新[!!]两个答案都给出了正确的结果,但是根据odan的信息,apokryfos的答案是干净的代码。感谢您的所有帮助。
答案 0 :(得分:2)
只需尝试
$imgs = Images::where('project_id', '=', $project->id)->get();
foreach($imgs as $i => $img) {
$img->order_id = $i + 1;
$img->save();
}
答案 1 :(得分:0)
$img
似乎是一个查询生成器对象。
如果您进行$img = Images::where('project_id', '=', $project->id)->get();
,将得到所有需要更新的示例:
$index = 1;
Images::where('project_id', '=', $project->id)->get()
->each(function ($img) use (&$index) {
$img->order_num = $index++;
$img->save();
});
这将更新单个项目ID的所有图像索引。如果您想全部完成,则可以执行以下操作:
$index = 0;
$lastProjectId = null;
Images::orderBy('project_id')->get()
->each(function ($img) use (&$index, $lastProjectId) {
if ($lastProjectId == null) {
$lastProjectId = $img->project_id;
}
if ($img->project_id != $lastProjectId) {
$index = 1;
$lastProjectId = $img->project_id;
}
$img->order_num = $index++;
$img->save();
});