使用yii2中的联结表对gridview进行筛选和排序

时间:2015-03-09 20:01:09

标签: php sql gridview yii2

我有3张桌子:

TABLE projects (
    id SERIAL PRIMARY KEY,
    name text NOT NULL,
);
TABLE project_participants (
    id SERIAL PRIMARY KEY,
    proj_id integer REFERENCES projects (id) NOT NULL,
);
TABLE valuations (
    id SERIAL PRIMARY KEY,
    proj_partic_id integer REFERENCES project_participants (id) NOT NULL,
    tehn_knowledge numeric NOT NULL,
    comunication_skills numeric NOT NULL,
);

和Projects模型中的函数:

    public function  getValuations() {
    return $this->hasMany(Valuations::className(), ['proj_partic_id' => 'id'])
        ->viaTable('project_participants', ['proj_id' => 'id']);
}

public function getValuationsSum() {
    $sum = 0;
    foreach ($this->valuations as $val){

        $sum += $val->tehn_knowledge;
        $sum += $val->comunication_skills;
    }
    return $sum;
}

因此在gridview中我可以显示如下的摘要数据:

        'columns' => [
                    'valuationsSum',

但是现在我想搜索和过滤值,但不能在projectsSearch模型中编写工作查询。 :(试过:

        $query = Projects::find();

    $subQuery = Valuations::find(Valuations::className(), ['proj_partic_id' => 'id'])
        ->viaTable('project_participants', ['proj_id' => 'id'])
        ->select('proj_partic_id, SUM(tehn_knowledge + comunication_skills) as rating')
        ->groupBy('project_participants.id');

    $query->leftJoin([
        'valuation'=>$subQuery
    ]);

以及$this->load($params);

之后

添加了

$query->andFilterWhere([
           'valuation.rating' => $this->valuationsSum,

但似乎这个$ subQuery绝对是错误的。试图写它类似于示例here,但我有这个联结表。

0 个答案:

没有答案