- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
嘿,大家好,我正在尝试开发一个查询,该查询从数据库返回热门文章。
热门文章基于过去 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排序的)
感谢帮助
最佳答案
您可以采取多种方法,
就像 @Oli 所说,在表中添加一列,用于保存过去 24 小时的 number_views,数据库中的触发器将使其保持最新。就像每次有 View 时它都会重新计算字段一样。
添加附加的 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
第三个选项是使用 SQL,它看起来像这样:https://laracasts.com/discuss/channels/general-discussion/eloquent-order-by-related-table
关于sorting - 制定趋势查询 - Laravel Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36613857/
我需要帮助制定 SQL 语句。这些表是 视频(video_id,描述,价格,category_id) 类别(category_id,描述) 查询需要生成一个摘要列表,显示属于每个类别的视频数量。未分配
我正在 Angular 1.5 中构建一个应用程序,并且我自己完成所有 CSS 等工作。到目前为止,我一直在通过在所有 html 模板中包含以下代码来处理错误和成功消息 然后我在处理错误/成
这是我在检查器上看到的: 两个规则中有一个左高亮,这是 Firefox 正在编写的规则,如果我查看计算样式,我会看到: 最后这是原始 CSS 的样子: 所以 Firefox 正在以某种方式改变位置和宽
我有两个系统 A 和 B。A 是 TCP Client,向 B 上的 TCP Server 发送消息。 ------------------ --------------
我是安卓新手。我想从 MainActivity.class 接收整数和字符串,并将其打印在 DisplayMessageActivity.class 中。从我在网上找到的所有解决方案中,他们说我应该使
我请求帮助了解如何使用 javax.persistence.criteria 包制定“in”条件。 我正在根据 Contacts 类的搜索条件创建 CriteriaQuery。一个联系人可以属于 0
我正在使用具有浮点坐标的 3D 向量进行计算。有时,我想检查一个向量是否非零。但是,对于 float ,总是有可能出现舍入错误。 Python 中是否有一种标准方法来检查 float 是否足够接近于零
这是一个愚蠢的问题,但我试图通过 Google、代码片段、教程来解决这个问题,所有这些都引导我找到一些示例,其中模型对于我想要执行的编码来说太浅了。 我想开发一个应用程序,其中数据采用 parent
我是一名优秀的程序员,十分优秀!