【发布时间】:2021-08-02 07:00:33
【问题描述】:
我在 Laravel 中创建了一个按任务计划运行的命令。
命令逻辑如下:
public function handle()
{
$commentNotifications = CommentNotification::where('task_performed', 0)
->get();
foreach ($commentNotifications as $commentNotification) {
//blah blah
}
$commentNotifications->update(['task_performed' => 1]);
$this->comment(sprintf('Completed %d CommentNotification(s)', $commentNotifications->count()));
}
但是这会返回以下错误:
方法 Illuminate\Database\Eloquent\Collection::update 不存在。
所以我尝试了这个:
$commentNotifications->task_performed = 1;
$commentNotifications->save();
但这返回了:
方法 Illuminate\Database\Eloquent\Collection::save 不存在。
为什么会这样?
【问题讨论】:
-
您无法更新收藏。在循环中使用
$commentNotification->update(['task_performed' => 1]);。 -
但是我在那个循环中有数千条记录。这将导致成千上万的查询......
-
在这种情况下,创建一个新查询并像这样更新它:
CommentNotification::where('task_performed', 0)->update(['task_performed' => 1]);
标签: laravel