1

I have user and post table with oneToMany relation:

In Post Model:

public function getUser() {
    return $this->hasOne(User::className(), ['id' => 'user_id']);
}

And in User Model:

public function getPosts() {
    return $this->hasMany(Post::className(), ['user_id' => 'id']);
}

I want find All users that has at least a active post. But I don`t have any idea.

My target SQL :

SELECT * FROM `user`
where id in (select user_id from post where status = 1)

What do I do?

User::find()->where(...

notice: its important that created with find(), because I want use it in search model

Thanks.

ingenious
  • 764
  • 2
  • 8
  • 24

3 Answers3

1

Best way:

User::find()->joinWith(['posts' => function(ActiveQuery $q){
    $q->where(['status' => 1]);
}])->all();
Vitaly
  • 1,261
  • 2
  • 10
  • 20
1

You need add a condition using where.

It is recommend that(It query speed is faster than other):

$condition = <<<EOL
EXISTS (
       SELECT 1 from post t2 
       WHERE (t1.id = t2.user_id) 
              AND (t2.status = 1)
)
EOL;

User::find()->from(['t1'=>User::getTableSchema()->name])
    ->where(new yii\db\Expression($condition))
    ->all();
HeadwindFly
  • 774
  • 3
  • 8
  • 19
0

You can use literal where however using User::find()

 User::find()->where('id in (select user_id from post where status = 1)');
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107