Laravel 4如何合并数据库表并通过created_at对它们进行排序?

时间:2022-01-29 12:13:26

I have 4 database tables that I want to merge together, and than I want to order all the data by created_at field. With my code all data is still grouped per database table, the result should be some sort of timeline of all my tables data. What am I doing wrong? It is only showing 4 items...

我有4个数据库表,我想合并在一起,而不是我想通过created_at字段订购所有数据。使用我的代码,所有数据仍然按数据库表分组,结果应该是我所有表数据的某种时间轴。我究竟做错了什么?它只显示4个项目......

public function showIndex()
{

    $users = User::orderBy('created_at', 'desc')->get();
    $projects = Project::with('votes')->orderBy('created_at', 'desc')->get();
    $events = Calendar::orderBy('created_at', 'desc')->get();
    $jobs = Job::orderBy('created_at', 'desc')->get();

    $all = $users->merge($projects)->merge($events)->merge($jobs);

    return View::make('users.index')->with('events', $all);

}

1 个解决方案

#1


Assuming the only problem is the fact that it's not order properly, you can simply use

假设唯一的问题是它没有正确排序,你可以简单地使用

$all->sort(function ($a, $b) {
    if ($a->created_at === $b->created_at) {
        return 0;
    } 

    return $a->created_at > $b->created_at ? 1 : -1;
});

or

$all = $all->sortBy(function($result) {
    return $result->created_at;
});

see http://laravel.com/api/master/Illuminate/Support/Collection.html#method_sort

#1


Assuming the only problem is the fact that it's not order properly, you can simply use

假设唯一的问题是它没有正确排序,你可以简单地使用

$all->sort(function ($a, $b) {
    if ($a->created_at === $b->created_at) {
        return 0;
    } 

    return $a->created_at > $b->created_at ? 1 : -1;
});

or

$all = $all->sortBy(function($result) {
    return $result->created_at;
});

see http://laravel.com/api/master/Illuminate/Support/Collection.html#method_sort