【问题标题】:Laravel ordering current to end dateLaravel 订购当前到结束日期
【发布时间】:2018-10-03 16:55:39
【问题描述】:

如果 current datestarts_atends_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_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

【问题讨论】:

  • 为什么E是第一位的?因为它从“今天”开始?
  • 是,其他为空、过期或未来日期。
  • 如果start_date 是昨天而end_date 是今天/明天呢?
  • 如果Estarts_at是昨天,ends_at是今天,E将被视为expired。如果Eends_at 是明天,那么E 将排在第一位。 Incase 2 或更多与E 相同,它们将按其创建时间排在最前面。

标签: mysql laravel laravel-5 eloquent


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    这个查询将极大地受益于 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_atstarts_at 等于null 的行。最后,从最新到最旧的订单。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 2011-09-24
      • 2019-08-07
      • 2012-07-25
      • 2014-03-02
      • 1970-01-01
      相关资源
      最近更新 更多