在 yii2 中对多个表使用连接

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

问题描述

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

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

并且我为关系添加了这两个函数:

公共函数 getfans() {return $this->hasOne(Fans::className(), ['id' => 'from_id'])->from(fans::tableName() . 'FBF');}公共函数 getComments() {return $this->hasMany(Comments::className(), ['parent_id' => 'id'])->from(comments::tableName() .'FBC');}

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

解决方案

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

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

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

解决方案

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 中对多个表使用连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)