在AR中正确使用AndWhere过滤器

时间:2018-10-30 12:34:57

标签: activerecord yii2

我正在使用以下查询来获取总数,以在Gridview上方显示一个小的仪表板图。

我想知道在选择管理器(registration_id)和选择ALL(不使用registration_id参数)时此查询的正确工作方式。

索引查看文件

$total_received_quota = Quota::find()
        ->where(['quota_status'=> 1])
        ->AndWhere(['quota_registration_id' => $manager])
        ->sum('quota_valor');

CONTROLLER

public function actionIndex()
{
    $searchModel = new QuotaSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    $manager = Yii::$app->getRequest()->getQueryParam('QuotaSearch')['quota_registration_id'];
    $manager = isset($manager) ? $manager : null;

    return $this->render('index', [
        'searchModel'   => $searchModel,
        'dataProvider'  => $dataProvider,
        'manager'       => $manager,
    ]);
}

1 个答案:

答案 0 :(得分:1)

尝试这种方式:

 $query= Quota::find()->where(['quota_status'=> 1]);

    if(isset($manager) && $manager!=null)
    {
      $query->andWhere(['quota_registration_id' => $manager]);
    }

  $total_received_quota=  $query->sum('quota_valor');