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...
}
我在这里做错了什么?非常感谢您的时间。
完美的作品。就像你建议的那样,我也切换到了“where”而不是'whereDate',以便不仅仅是一天的几分钟和几秒钟。非常感谢@Sandeesh。 – anonym
@anonym没问题:) – Sandeesh