【发布时间】:2018-10-03 16:55:39
【问题描述】:
如果 current date 在 starts_at 和 ends_at 日期之内/之间,我如何在 laravel/mysql 中 orderBy 日期?
例如:
// 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_at 和ends_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。
【问题讨论】:
-
为什么
E是第一位的?因为它从“今天”开始? -
是,其他为空、过期或未来日期。
-
如果
start_date是昨天而end_date是今天/明天呢? -
如果
E的starts_at是昨天,ends_at是今天,E将被视为expired。如果E的ends_at是明天,那么E将排在第一位。 Incase 2 或更多与E相同,它们将按其创建时间排在最前面。
标签: mysql laravel laravel-5 eloquent