php 在 yii2 中对多个表使用连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23606740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:50:18  来源:igfitidea点击:

use Joins for multiple tables in yii2

phpleft-joinyii2

提问by ruba

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:

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

<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 ??

这给了我写帖子的粉丝的帖子和数据及其评论,但我需要的是也写评论的粉丝的数据,那么我如何将评论加入粉丝表?

回答by davey

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

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

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