use Joins for multiple tables in 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 中对多个表使用连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 yii2 中对多个表使用连接
基础教程推荐
- 在多维数组中查找最大值 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01