首页 > 解决方案 > 在 AR 中正确使用 AndWhere 过滤器

问题描述

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

I would like to know the correct way for this query to work both when a manager is selected ( registration_id) and when ALL (without the registration_idparameter) is selected.

索引查看文件

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

控制器

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,
    ]);
}

标签: activerecordyii2

解决方案


试试这种方式:

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

推荐阅读