仅当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_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。
答案 0 :(得分:0)
尝试一下:
Example::orderBy('ends_at','desc')->latest()->get();
答案 1 :(得分:0)
Laravel非常出色的Query Buider使该查询受益匪浅。
尝试一下:
Example::where([
['ends_at', '>=', Carbon::now()],
['starts_at', '<=', Carbon::now()],
['ends_at', '!=', null],
['starts_at', '!=', null]
])
->orderBy('ends_at','desc')
->get();
这应该使您接近所需的内容。根据表的列类型,您可能必须稍微修改Carbon
对象的格式,以便比较不会引发错误。
即。
Carbon::now()->format('Y-m-d') // 2018-10-04
它还确保不显示ends_at
和starts_at
等于null
的行。最后,从最新到最旧订购。
希望这会有所帮助!