gpt4 book ai didi

sorting - 制定趋势查询 - Laravel Eloquent

转载 作者:行者123 更新时间:2023-12-02 10:50:07 25 4
gpt4 key购买 nike

嘿,大家好,我正在尝试开发一个查询,该查询从数据库返回热门文章。

热门文章基于过去 24 小时内最多的浏览次数。这是到目前为止的代码:

$trending = Article::whereHas('view', function ($query) {
$query->where('created_at', '>=', Carbon::now()->subHours(24));
})
->with('view')
->orderBy('created_at', 'DESC')
->get();

return $trending;
}

文章模型有以下关系:

public function view()
{
return $this->hasMany('ArticleView', 'article_id');
}

查询有效,但我不知何故还需要按 View 计数对文章进行排序。例如,显示当前热门文章,但浏览次数最多的文章并不是从头到尾排序的(显然 - 它们是按created_at排序的)

感谢帮助

最佳答案

您可以采取多种方法,

  1. 就像 @Oli 所说,在表中添加一列,用于保存过去 24 小时的 number_views,数据库中的触发器将使其保持最新。就像每次有 View 时它都会重新计算字段一样。

  2. 添加附加的 24h_views_count 运行查询,然后在代码中排序

    protected $appends= ['24h_views_count']

    public get24hViewsCountAttribute(){
    return $this->view()->where('created_at', '>=', Carbon::now()->subHours(24))->count();
    }

    //and after you get the result from trending just sort the collection via that property.
    $trending->sortByDesc('24h_views_count');//this will sort it from highest to lowest
  3. 第三个选项是使用 SQL,它看起来像这样:https://laracasts.com/discuss/channels/general-discussion/eloquent-order-by-related-table

关于sorting - 制定趋势查询 - Laravel Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36613857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com