Yii2 gridview来自联结表的任意列数

Let's say I have "record", "category", "group" tables and models.

Relations are:

  • record has many category (junction)
  • category has many groups enter image description here

What I want to do here is;

If there are two categories and those categories have several groups. For each record I want to choose a group for each category. Until here there is no problem.

At the page "record/index", in the gridview I would like to show and filter those groups for each category.

To do that I need to add arbitrary number of columns (in this scenario it is two for two categories) to gridview. This is also doable but filtering and sorting seems not possible.

My search method is:

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;
}

In the view I tried this code:

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

and it does not work :(

What should I change in search model and index.