简体   繁体   中英

Many to Many Relation query in 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

How to write above query in Yii 2 using ActiveQueryInterface methods

If you are using ActiveRecords you can create relation like this in Content class:

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

Use AcitveQuery and innerJoin()

$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM