Yii2 subquery in Active Record

Ngoun Thavy picture Ngoun Thavy · May 11, 2015 · Viewed 30.4k times · Source

How can I convert this sql into active record query

SELECT * FROM `base_twitter` WHERE id NOT IN (SELECT base_id from base_followers)

Answer

arogachev picture arogachev · May 11, 2015

Assuming that your models are named BaseTwitter and BaseFollower accordingly, this should work:

$subQuery = BaseFollower::find()->select('id');
$query = BaseTwitter::find()->where(['not in', 'id', $subQuery]);
$models = $query->all();