Yii2中的多对多关系查询

时间:2018-12-27 11:03:14

标签: php yii yii2

SELECT c.* 
from content c 
inner join contentTags ct on c.id = ct.content 
inner join tags t on ct.tag = c.id 
where t.id = 1

如何使用ActiveQueryInterface方法在Yii 2中编写以上查询

2 个答案:

答案 0 :(得分:2)

如果您使用的是ActiveRecords,则可以在Content类中创建如下关系:

public function getTags()
{
    return $this->hasMany(Tag::className(), ['id' => 'tag'])
                    ->viaTable('contentTags', ['content' => 'id']);
}

答案 1 :(得分:1)

使用AcitveQueryinnerJoin()

$data = (new \yii\db\Query())
    ->select('c.*')
    ->from('content c')
    ->innerJoin('contentTags ct', 'c.id = ct.content')
    ->innerJoin('tags t', 'ct.tag = c.id')
    ->where(['t.id' => 1])
    ->all();
相关问题