Php (laravel)两个有序条款和一个限制
这是一些分类:Php (laravel)两个有序条款和一个限制,php,sql,laravel,Php,Sql,Laravel,这是一些分类: 我想根据“观点”列出20篇最好的帖子 然后,根据“created_at”对其进行排序 怎么做 以下是我当前的代码(可以使用,但不按“created_at”排序): 你可以写这个。希望这能解决你的问题 $this->data['today_post'] = Posts::orderBy('views', 'desc') ->orderBy('created_at', 'desc') ->whereDate('created_at', Carbon::today(
你可以写这个。希望这能解决你的问题
$this->data['today_post'] =
Posts::orderBy('views', 'desc')
->orderBy('created_at', 'desc')
->whereDate('created_at', Carbon::today()->toDateString())
->limit(20)
->get();
同时添加
使用碳\碳代码>在控制器的开头。首先从数据库获取一个集合
$x = Posts::whereRaw('created_at >= NOW() - INTERVAL 1 DAY')->orderBy('views', 'desc')->limit(20)->get();
然后对集合进行排序
降序:
$this->data['today_post'] = $x->sortByDesc('created_at');
升序:
$this->data['today_post'] = $x->sortBy('created_at');
您可以简单地对结果集合进行排序。保留您的代码,添加以下内容:
$this->data['today_post'] = $this->data['today_post']->sortBy('created_at');
不起作用。你可以从我的标题中看出,我的问题不是“日期”。我的问题是分类。我想分类两次。第一种按视图排序限制为20。然后按时间排序(desc)。@dobieme我提供的代码在我的系统中运行良好。请看一看您的表结构。是的,它确实有效,但不按“created_at”排序(很好!您能将其标记为解决方案吗?那太好了,因为这是我的第一个正确答案:)
$this->data['today_post'] = $this->data['today_post']->sortBy('created_at');