我有 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 循环中显示它们。
请让我知道您认为最好的做法是。谢谢!
我会利用Eloquent的多态关系来解决这个问题。从本质上讲,您的三个表有一个共同点,因为它们都是活动,或者由于缺乏更好的术语而"可激活"。请参阅:https://laravel.com/docs/master/eloquent-relationships#polymorphic-relations