我有3个名为comments
,post
,feedback
的表格。
在个人资料页面中,用户可以看到某人的活动。例如,如果他们发表评论和发帖,他们可以看到类似
的内容 8:00 AM John has commented on this thread.
9:00 PM Jack has posted a new post
。
问题在于我不知道如何在一个foreach循环中组合所有这些记录。
我现在的foreach循环很简单:
foreach ($posts as $post) {
echo 'User has made a new post: ' . $post->post;
}
foreach ($feedback as $feed) {
echo 'User has given a new feedback: ' . $feedback->feedback;
}
foreach ($comments as $comment) {
echo 'User has made a new comment: ' . $comment->comment;
}
正如您所看到的,我有3个foreach
循环。我想要像
foreach ($activities as $activity) {
if ($activity->type == 'comment')
echo "User can made a new comment: $activity->comment";
if ($activity->type == 'post)
echo "User has made a new post: $activity->post";
}
我希望这是有道理的。基本上,我想将所有三个表合并为一个,然后在Recent User Activity
页面的foreach循环中显示它们。
请让我知道你认为最好的做法是什么。谢谢!
答案 0 :(得分:0)
我会利用Eloquent的多态关系。基本上你的三个表有一个共同点,那就是它们都是活动,或者因为缺乏更好的术语而“可激活”。请参阅:https://laravel.com/docs/master/eloquent-relationships#polymorphic-relations