【发布时间】:2021-10-09 22:11:09
【问题描述】:
在我的 Laravel 应用程序中,用户可以对提交的内容投赞成票或反对票。
为了计算提交的总分,我不会在每次投票时都这样做,因为这会导致大量查询。
相反,每隔几分钟,我使用 Laravel 的任务调度器运行一个任务,获取所有最近提交的内容,然后计算每个提交的总分。
任务命令:
$submissions = Submission::where('created_at', '>', Carbon::now()->subDays(2))
->withCount('upVotes')
->withCount('downVotes')
->get();
$submissions->each(function ($item) {
$item->total_upvotes = $item->up_votes_count;
$item->total_downvotes = $item->down_votes_count;
$item->total_score = $this->score($item->up_votes_count, $item->down_votes_count);
$item->hotness = $this->hotness($item->up_votes_count, $item->down_votes_count, $item->created_at->timestamp);
$item->save();
});
但是,我担心当扩展到每天可能有数千个提交时,这可能无法很好地工作。也许这个任务会超时?
或者,我可以让命令调度一个执行 foreach 的作业,而不是在任务调度程序命令中执行 foreach,如下所示:
任务命令:
$submissions = Submission::where('created_at', '>', Carbon::now()->subDays(2))
->withCount('upVotes')
->withCount('downVotes')
->get();
//DISPATCH QUEUE JOB
队列作业:
$submissions->each(function ($item) {
$item->total_upvotes = $item->up_votes_count;
$item->total_downvotes = $item->down_votes_count;
$item->total_score = $this->score($item->up_votes_count, $item->down_votes_count);
$item->hotness = $this->hotness($item->up_votes_count, $item->down_votes_count, $item->created_at->timestamp);
$item->save();
});
这样会更好吗?
【问题讨论】: