【问题标题】:Iterate through every row in 3 tables in one foreach loop - PHP - Laravel在一个 foreach 循环中遍历 3 个表中的每一行 - PHP - Laravel
【发布时间】:2016-03-14 00:06:45
【问题描述】:

我有 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 循环中显示它们。

请告诉我您认为最好的做法是什么。谢谢!

【问题讨论】:

    标签: php mysql laravel foreach


    【解决方案1】:

    我会为此利用 Eloquent 的多态关系。本质上,您的三个表有一个共同点,因为它们都是活动,或者“可激活”,因为没有更好的术语。见:https://laravel.com/docs/master/eloquent-relationships#polymorphic-relations

    【讨论】:

      猜你喜欢
      • 2014-06-29
      • 1970-01-01
      • 2015-04-14
      • 2015-06-16
      • 1970-01-01
      • 2011-03-09
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多