Yii2 subquery in Active Record

后端 未结 3 1046
无人共我
无人共我 2020-11-29 06:14

How can I convert this sql into active record query

SELECT * FROM `base_twitter` WHERE id NOT IN (SELECT base_id from base_followers)
相关标签:
3条回答
  • 2020-11-29 06:34

    Try This Query

    $models = BaseTwitter::find()->where('id NOT IN (SELECT base_id from base_followers)')->all();
    
    0 讨论(0)
  • 2020-11-29 06:35
    // 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]);
    
    0 讨论(0)
  • 2020-11-29 06:48

    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();
    
    0 讨论(0)
提交回复
热议问题