我有一个模型tasks
,其中包含过去datetime
的完整任务以及 future datetime
即将执行的任务。
在检索任务时,我想按升序显示即将到来的任务(从现在到 future ),并按降序显示过去的任务(从现在到过去)。
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...
}
我在这里做错了什么?非常感谢您的宝贵时间。
最佳答案
两个结果都是一个集合。您可以使用集合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
条件,因此您会丢失基于查询的当前日期的所有数据。您可能想检查一下。
关于Laravel 查询生成器 : How do I sort results by date - first with ascending order by future dates and then by descending order by past dates?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44352203/