通过时间戳created_at合并模型和排序

时间:2018-05-01 16:59:41

标签: laravel laravel-5 laravel-5.4

我正在创建一个活动页面,它将显示用户的活动,并且我想知道解决此问题的最佳方法,即显示不同活动并在所有合并的表的created_at时间戳上对活动进行排序

此刻我

控制器

    public function getActivity()
      {
        $blogs = Blogs::where('blogs.user_id', '=', Auth::User()->id)->orderBy('created_at', 'DESC')
        $comments = Comments::where('comments.user_id', '=', Auth::User()->id)- >orderBy('created_at', 'DESC')
        $forumposts = Forumpost::where('forumposts.user_id', '=', Auth::User()->id)->orderBy('created_at', 'DESC')

        return view('myactivity')->withBlogs($blogs)->withComments($comments)->withForumposts($forumposts);

      }

查看:

@foreach($blogs as $blog)
    <p>You posted {{$blog->blogname}} at {{$blog->created_at}}</p>

@endforeach 
@foreach($comments as $comment)
    <p>You posted {{$comment->comment}} at {{$comment->created_at}}</p>

@endforeach 
@foreach($forumposts as $forumpost)
    <p>You posted {{$forumpost->post}} at {{$forumpost->created_at}}</p>

@endforeach 

上面代码的问题是它没有在一个created_at上合并,它本质上是三个不同的created_at列表,我如何将它们合并为一个?

1 个答案:

答案 0 :(得分:1)

试试这个:

$activities = $blogs->toBase()
    ->merge($comments)
    ->merge($forumposts)
    ->sortByDesc('created_at');

->toBase()是必要的,否则会合并具有相同id的模型。

然后在您的视图中区分它们:

@foreach($activities as $activity)
    @if($activity instanceof \App\Blogs)

    @endif
@endforeach