[英]Iterate through every row in 3 tables in one foreach loop - PHP - Laravel
我有3个表,分别是comments
, post
, feedback
。
在个人资料页面中,用户可以查看某人的活动。 例如,如果他们发表评论和发布信息,他们会看到类似
8:00 AM John has commented on this thread. 9:00 PM Jack has posted a new post
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.