在yii2中对多个表使用Joins [英] use Joins for multiple tables in yii2

查看:70
本文介绍了在yii2中对多个表使用Joins的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用yii2,我有3个表:帖子,粉丝,评论,并且我想使用joinWith()来获取带有评论和粉丝名称(在粉丝表中)的帖子和评论. 我写的是这个查询:

I am using yii2, I have 3 tables: posts, fans, comments and i want to use joinWith() to get the posts with their comments and the fan name (in fans table) for post and comments. what i wrote is this query:

<pre>
 facebook_posts::find()->joinwith('fans')->joinWith('comments')->all();
</pre>

我为关系添加了这两个功能:

and I added these two functions for the relations:

<pre>
    public function getfans() {
        return $this->hasOne(Fans::className(), ['id' => 'from_id'])->from(fans::tableName() . ' FBF');
    }
    public function getComments() {
        return $this->hasMany(Comments::className(), ['parent_id' => 'id'])->from(comments::tableName() . ' FBC');
    }
</pre>

这给了我帖子的内容以及撰写该帖子及其评论的粉丝的数据,但是我需要的是也写评论的粉丝的数据,所以我该如何在粉丝表中加入评论?

this gives me the posts and the data of the fan who wrote the post and its comments but what i need is the data of fan that wrote the comments also, so how can i join comments with fans table ??

推荐答案

确保您的Comments模型中具有fan关系,然后您可以使用以下内容获取每个帖子的所有评论以及粉丝关系对于每个评论:

Make sure you have a fan relation in your Comments model, then you can use the following to get all comments for each post and the fan relation for each comment:

facebook_posts::find()->joinWith('fans')->joinWith(['comments', 'comments.fan'])->all();

这篇关于在yii2中对多个表使用Joins的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆