laravel排序当前结束日期

neekobn8  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(248)

我该怎么办 orderBy 仅当 current date 在/之间 starts_at 以及 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

这是我的小提琴。

p8ekf7hl

p8ekf7hl1#

这个查询将从laravel相当惊人的查询构建器中获益匪浅。
试试这个:

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 未显示。最后,从最新到最老的订单。
希望这有帮助!

58wvjzkj

58wvjzkj2#

试试这个:

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

相关问题