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 中对多个表使用连接
基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何替换eregi() 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
