【问题标题】:conditional `orderBy` or `DB::Raw` inside `orderBy` in LaravelLaravel 中 `orderBy` 中的条件 `orderBy` 或 `DB::Raw`
【发布时间】:2019-07-27 14:28:08
【问题描述】:

我正在尝试在asc 订单中显示从今天开始的特定未来几天的预约列表。(例如:接下来的 5 天或 10 天)。仅从今天开始,接下来的 5 天或 10 天(注意:天将是动态的,我的意思是客户将设置)。当 today 日期将结束时,此日期不应进入我的日子提到(从今天到接下来的 5 天)。我正在尝试使用orderBy 方法,如下所示 -

$today = date('Y-m-d');
$appointments = Appointment::with('Customer')
         ->orderBy(DB::raw("('appointment_time', '>=', ${today})"), 'asc')->get();

return view("ManageAppointment", compact(['appointments']));

当然,我收到以下错误 -

SQLSTATE[21000]:基数违规:1241 操作数应包含 1 列(SQL:select * from appointments order by ('appointment_time', '>=', 2019-07-27) asc)

我应该怎么做才能得到预期的结果,有人可以帮我吗?

【问题讨论】:

  • 您需要按哪些列排序??
  • 试试这个:DB::raw("(appointment_time >= '${today}')")

标签: mysql laravel laravel-5 eloquent sql-order-by


【解决方案1】:

试试看。

$tomorrow = Carbon::tomorrow(); //2019-07-28 00:00:00
$nextdate = Carbon::now()->addDays(5); //dynamic day(5days, 10days) //2019-08-01 00:00:00

$appointments = Appointment::with('Customer')
                      ->whereBetween('appointment_time', [$tomorrow,$nextdate])
                      ->orderBy('appointment_time','asc')->get();

【讨论】:

    【解决方案2】:

    您可以使用 WHERE 子句而不是 ORDER BY 这样做:

    <?php 
    
        $current_date = date('Y-m-d H:i:s');
        $next5Days = date('Y-m-d H:i:s',strtotime('+5 days'));
        $appointments = Appointment::with('Customer')
               ->where('appointment_time','>=',$current_date)
               ->where('appointment_time','<=',$next5Days)
         ->orderBy('appointment_time', 'asc')->get(); 
    ?>
    

    这将产生类似的东西。

    SELECT * from appointments_table where appointment_time <= 2019-07-27 18:30:58 
    AND where appointment_time <= 2019-08-31 00:00:00 ORDER BY appointment_time ASC
    

    希望它对你有用! :)

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 2015-08-06
      • 2013-12-27
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      相关资源
      最近更新 更多