Yii2,找到活跃的用户 post

Yii2, find users that has active post

我有 userpost table 与 oneToMany 关系:

在Post型号中:

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

并且在用户模型中:

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

我想找到至少有一个活跃 post 的所有用户。 但是我不知道。

我的目标SQL:

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

我该怎么办?

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

注意:使用 find() 创建的很重要,因为我想在搜索模型中使用它

谢谢。

您可以使用文字 where 但是使用 User::find()

 User::find()->where('id in (select user_id from post where status = 1)');

最佳方式:

User::find()->joinWith(['posts' => function(ActiveQuery $q){
    $q->where(['status' => 1]);
}])->all();

您需要使用 where 添加条件。

推荐(查询速度比其他的快):

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