Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 subquery in Active Record

Tags:

How can I convert this sql into active record query

SELECT * FROM `base_twitter` WHERE id NOT IN (SELECT base_id from base_followers) 
like image 839
Ngoun Thavy Avatar asked May 11 '15 09:05

Ngoun Thavy


2 Answers

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(); 
like image 180
arogachev Avatar answered Oct 26 '22 06:10

arogachev


// SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`; $subquery = (new \yii\db\Query)->from('user')->where(['active' => true]) $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);  // subquery can also be a string with plain SQL wrapped in parenthesis // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`; $subquery = "(SELECT * FROM `user` WHERE `active` = 1)"; $query = (new \yii\db\Query)->from(['activeusers' => $subquery]); 
like image 26
Oleg Avatar answered Oct 26 '22 07:10

Oleg