Laravel。相同的列顺序两次

时间:2015-01-27 13:20:04

标签: laravel

我有帖子,想按日期提升订购,另外我希望今天之前的帖子会在其他帖子之后发布。我怎么能这样做?

现在我只得到了这个:

$posts = Post::orderBy('date', 'asc')->get();

2 个答案:

答案 0 :(得分:1)

您需要使用orderByRaw

$posts = Post::orderByRaw('DATE(`date`) < CURDATE()')
               ->orderBy('date', 'asc')
               ->get();

答案 1 :(得分:0)

I have posts and want to order by date ascend, plus I want that posts where date is before today will go to after other posts

也许这符合您的需求:

  1. 首先,您需要按$current = Carbon::now()
  2. 获取当前时间
  3. 当发布时间落后于今天时,按当前时间加上发布时间,旧帖子将放在结果的后面。否则按当前时间减去发布时间,较新的帖子将位于前面。以下是查询:Post::select('id', 'date', DB::raw('(CASE when date < '.$current.' then date+'.$current.' else date-'.$current.' END) AS new_post_time'))->orderBy('new_post_time', 'asc')->get();
  4. 现在,您可以看到提取的帖子id以及原始帖子date。如果您不需要,请忽略new_post_time列。

    希望这会有所帮助。我自己没有运行查询。可能存在一些错误。