我有3个表,分别为commentspostfeedback

在个人资料页面中,用户可以查看某人的活动。例如,如果他们发表评论和发布信息,他们会看到类似

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

关于php - 在一个foreach循环中遍历3个表中的每一行-PHP-Laravel,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35977534/

10-13 08:59