Yii2如何将where子句中的cascade select转换为activequery?

时间:2016-11-11 15:47:13

标签: mysql sql yii2

两个表questionanswer,我需要为特定用户转储所有未回答的问题。在sql中

select * from question where question.user_id = user_id
and (select count(*) from answer where answer.question_id = question.id) = 0

但我怎么能把这个命令变成activequery?

Question::find()->where(['user_id' => user_id]) ....

2 个答案:

答案 0 :(得分:1)

用于查找没有答案的给定用户的每个问题的活动查询。

Question::find()->leftJoin('answer', 'answer.question_id=question.id')
                ->where(['question.user_id' => $user_id])
                ->andWhere(['answer.id' => null)

答案 1 :(得分:1)

您的查询可以这样写

  select * from question 
  inner join answer on answer.question_id = question.id
  where question.user_id = user_id
  group by question.id 
  having count(*) > 0

并且在activeRecored中你可以使用

 Question::find()->innerJoin('answer', answer.question_id = question.id)->
        where(['user_id' => user_id])->
        groupBy('id')->
        having('having count(*) > 0')->