Yii2过滤器在GridView中求和数据

时间:2016-11-03 23:51:21

标签: php gridview yii2

我试图通过SQL SUM运算符显示和过滤数据。 我有2名员工和部门。表员工包含department_id归档和工资。我需要显示每个部门的所有部门和总工资。 我遵循了这个guide,但GridView不显示任何数据。 这是行动:

public function actionIndex()
{
    $searchModel = new DepartmentFrontendSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    return $this->render('index',
        [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,

        ]
    );
}

型号:

class DepartmentFrontendSearch extends DepartmentFrontend

public $employee_count;
public $salary;


public function rules() {
    return [

        [['employee_count','salary','name'], 'safe']
    ];
}

public function search($params) {

    $query = DepartmentFrontend::find();
    $subQuery = Employee::find()
        ->select('department_id, SUM(salary) as salary_amount')
        ->groupBy('department_id');
    $query->leftJoin(['salarySum' => $subQuery], 'salarySum.department_id = id');

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);
    $dataProvider->setSort([
        'attributes' => [
            'name',
            'salary'
        ]
    ]);

    $this->load($params);

    if (!$this->validate()) {
        return $dataProvider;
    }

    $query->andFilterWhere(['like', 'name', $this->name]);
    $query->andWhere(['salarySum.salary_amount' => $this->salary]);
    return $dataProvider;
}

GRID:

   echo GridView::widget([
   'dataProvider' => $dataProvider,
   'filterModel' => $searchModel,
   'columns' => [
       ['class' => 'yii\grid\SerialColumn'],
       'salary_amount',
       'employee_count',
       'name',

   ],

]);

那么,有谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:0)

如果你需要一个别名salary_amount的过滤器,你应该为此添加一个特定的var(事实上salary_amount是sum(salary)的别名,var $ salary是没用的)

public $employee_count;
public $salary;
public $salary_amount;

否则也使用薪水作为别名

您正在使用的过滤器

$query->andWhere(['salarySum.salary_amount' => $this->salary]);

但salary_amount是汇总的结果,因此您应该使用having(SUM(salary) = $this->salary_amount)

 $query->having('SUM(salary) = ' . $this->salary_amount);