合并模型并按时间戳排序 created_at
Merging models and ordering by timestamps created_at
我正在制作一个 activity 页面,它将显示用户的 activity,我想知道解决这个问题的最佳方法是显示不同的 activity 和在合并的所有表的 created_at 时间戳上排序 activity。
目前我有
控制器
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 列表,我如何将它们合并成一个?
试试这个:
$activities = $blogs->toBase()
->merge($comments)
->merge($forumposts)
->sortByDesc('created_at');
->toBase()
是必需的,否则具有相同 id
的模型将被合并。
然后在您看来区分它们:
@foreach($activities as $activity)
@if($activity instanceof \App\Blogs)
@endif
@endforeach
我正在制作一个 activity 页面,它将显示用户的 activity,我想知道解决这个问题的最佳方法是显示不同的 activity 和在合并的所有表的 created_at 时间戳上排序 activity。
目前我有
控制器
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 列表,我如何将它们合并成一个?
试试这个:
$activities = $blogs->toBase()
->merge($comments)
->merge($forumposts)
->sortByDesc('created_at');
->toBase()
是必需的,否则具有相同 id
的模型将被合并。
然后在您看来区分它们:
@foreach($activities as $activity)
@if($activity instanceof \App\Blogs)
@endif
@endforeach