在yii2中的andFilterWhere中的子查询

时间:2016-12-02 09:16:56

标签: php yii2 query-builder

我必须执行此查询

Agent.sources.Netcat.selector.type = replicating

我在yii2-

中写了这样的查询
select count(id) as numberofcompanies, sum(offered_value) as total_offered_value from campaign_comapany
       where ( campaign_id in (select id from campaing where user_id = current_user ) or campaing_company.sp_user_id = current_user)
             and campaign_company.status = '3'

但它给了我$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value']) ->from('campaign_company') ->andFilterWhere(['or',['in','campaign_id',(new yii\db\Query())->select(['id'])->from('campaign')->where(['=','user_id',Yii::$app->user->id])],['=','campaign_company.sp_user_id',Yii::$app->user->id]]) ->andWhere(['=','status','3']) ->one(); 的错误 但是如果我只是使用unknow column campaign_company.user_id就像下面那样工作 -

where

我应该怎么做才能得到sql查询的结果,我不想两次打到数据库服务器,提前谢谢

2 个答案:

答案 0 :(得分:1)

因为很难遵循你的逻辑。要简化代码和查询,请将第一个条件添加为普通sql。此外,由于需要第二个条件,您可以按如下方式交换位置:

$query
    ->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
    ->from('campaign_company')
    ->where(['status' => '3'])
    ->andWhere(['
        campaign_id in (select id from campaign where user_id = :current_user )
        or campaign_company.sp_user_id = :current_user1', 
        [':current_user' => Yii::$app->user->id, ':current_user1' => Yii::$app->user->id]])
    ->one();

答案 1 :(得分:1)

使用join:

$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
       ->from('campaign_company')
       ->innerJoin('campaign','`campaign`.`id` = `campaign_company`.`campaign_id`') 
       ->where([
           ['=','campaign.user_id',Yii::$app->user->id])],
           ['=','campaign.campaign_company.sp_user_id',Yii::$app->user->id],
           ['=','campaign_company.status','3']
         ]
       ->one();