1

我有一个模型tasks与完成任务与datetime在过去和即将到来的任务与datetime在未来。Laravel查询生成器:如何按日期排序结果 - 先按未来日期的升序排序,然后按过去日期的降序排序。

在检索任务时,我想显示按升序排列即将到来的任务(从现在到未来)以及过去按降序排列(从现在到过去)的任务。

public function getTasks() 
{ 
     $futureTasks = Task::whereDate('datetime', '>', Carbon::now())->orderBy('datetime', 'asc')->get(); 
     $pastTasks = Task::whereDate('datetime', '<', Carbon::now())->orderBy('datetime', 'desc')->get(); 
     $tasks  = array_merge($futureTasks, $pastTasks); 
     $response = ['tasks' => $tasks]; 
     // return... 
} 

,我发现了以下错误:

array_merge(): Argument #1 is not an array

如果我逆转参数的顺序为array_push功能,我仍然得到同样的错误。

public function getTasks() 
{ 
     $futureTasks = Task::whereDate('datetime', '>', Carbon::now())->orderBy('datetime', 'asc')->get(); 
     $pastTasks = Task::whereDate('datetime', '<', Carbon::now())->orderBy('datetime', 'desc')->get(); 
     $tasks  = array_merge($pastTasks, $futureTasks); 
     $response = ['tasks' => $tasks]; 
     // return... 
} 

,如果我只检索futureTasks或pastTasks没有array_merge,我得到所需的输出。

public function getTasks() 
{ 
     $futureTasks = Task::whereDate('datetime', '>', Carbon::now())->orderBy('datetime', 'asc')->get(); 

     $response = ['tasks' => $futureTasks]; 
     // return... 
} 

我在这里做错了什么?非常感谢您的时间。

回答

1

这两个结果都是一个集合。您可以使用集合merge方法。

public function getTasks() 
{ 
    $futureTasks = Task::whereDate('datetime', '>', Carbon::now()) 
     ->orderBy('datetime', 'asc') 
     ->get(); 

    $pastTasks = Task::whereDate('datetime', '<', Carbon::now()) 
     ->orderBy('datetime', 'desc') 
     ->get(); 

    $tasks = $futureTasks->merge($pastTasks); 
    $response = compact('tasks'); 
    // return... 
} 

由于您使用的whereDate条件,你错过了从根据您的查询本日的所有数据。你可能想检查一下。

+1

完美的作品。就像你建议的那样,我也切换到了“where”而不是'whereDate',以便不仅仅是一天的几分钟和几秒钟。非常感谢@Sandeesh。 – anonym

+0

@anonym没问题:) – Sandeesh