Yii2 gridview联结表中的任意列

时间:2019-02-21 20:07:02

标签: php mysql gridview yii2 yii2-model

假设我有“记录”,“类别”,“分组”表和模型。

关系是:

  • 记录有很多类别(交界处)
  • 类别有很多组 enter image description here

我想在这里做的是

如果有两个类别,并且这些类别具有多个组。 对于每个记录,我想为每个类别选择一个组。 到这里为止没有问题。

在“记录/索引”页面的网格视图中,我想显示和过滤每个类别的那些组。

为此,我需要向gridview添加任意数量的列(在这种情况下,两个类别为两个)。这也是可行的,但似乎无法进行过滤和排序。

我的搜索方法是:

public $categories;

public function rules()
{
    return [
        [[..., 'categories'], 'safe'],
    ];
}

public function search($params)
{
    $query = Record::find();

    $query->joinWith('recordToRecordCategories');

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => ['defaultOrder' => ['CreateDate' => SORT_DESC]],
        'pagination' => [
            'pageSize' => 50,
        ],
    ]);

    $this->load($params);

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

    // grid filtering conditions
    $query->andFilterWhere([
        'id' => $this->id,
        .
        .
    ]);

    // Here we search the attributes of our relations using our previously configured
    // ones in "record_to_record_category"
    if (!empty($this->categories)) {
        foreach ($this->categories as $category) {
            $query->andFilterWhere(['record_to_record_category.record_group_id' => $category]);
        }
    }

    return $dataProvider;
}

在视图中,我尝试了以下代码:

foreach ($recordCategories as $recordCategory) {
    array_push(
        $gridColumns,
        [
            'attribute' => 'categories[' . $recordCategory->id . ']',
            'label' => $recordCategory->name,
            'value' => function ($model, $key, $index, $column) {
                $returnVal = "";
                foreach ($model->recordToRecordCategories as $recordToRecordCategory) {
                    if ($recordToRecordCategory->recordCategory->name == $column->label) {
                        $returnVal = $recordToRecordCategory->recordGroup->name;
                    }
                }
                return $returnVal;
            },
            'filter' => ArrayHelper::map($recordCategory->getRecordGroups()->asArray()->all(), 'id', 'name'),
            'filterInputOptions' => [
                'class' => 'form-control',
                'prompt' => Yii::t('app', 'All')
            ],
        ]
    );
}

,它不起作用:(

我应该更改搜索模型和索引。

0 个答案:

没有答案
相关问题