首页 > 解决方案 > Laravel 订购当前到结束日期

问题描述

orderBy只有在日期current date范围内/之间starts_at,我如何才能在 laravel/mysql 中ends_at约会?

例如:

// Suppose Current Date: 2018-10-05

- Example A
  = Starts At: NULL,       Ends At: NULL,       Created At: 2018-10-05
- Example B
  = Starts At: NULL,       Ends At: NULL,       Created At: 2018-10-04
- Example C
  = Starts At: 2018-10-01, Ends At: 2018-10-03, Created At: 2018-10-03
- Example D
  = Starts At: 2018-10-03, Ends At: 2018-10-05, Created At: 2018-10-02
- Example E
  = Starts At: 2018-10-05, Ends At: 2018-10-07, Created At: 2018-10-01
- Example F
  = Starts At: 2018-10-07, Ends At: 2018-10-09, Created At: 2018-09-30

我当前的查询是(列是starts_atends_at):

Example::orderByRaw('if(isnull(starts_at) >= curdate() and isnull(ends_at) <= curdate(), starts_at, created_at) desc');

结果:

- Example A
- Example B
- Example C
- Example D
- Example E
- Example F

预期结果:

- Example E // First because of starts at 2018-10-05 until 2018-10-07
- Example A --
- Example B   |_ // Same order based expired/null
- Example C   |
- Example D --
- Example F // Still last because starts at is in the future

这是我的sqlfiddle

标签: mysqllaravellaravel-5eloquent

解决方案


尝试这个:

Example::orderBy('ends_at','desc')->latest()->get();

推荐阅读