V
V
Vitaliy2015-07-06 18:26:02
Yii
Vitaliy, 2015-07-06 18:26:02

Displaying Many to Many result in Yii 2 using GridView?

1. Three tables are given: Email, Categories, Emailcategories
2. Many to Many relationship is implemented (each email can be in different Categories)
3. Using a getter, I get a multidimensional array that contains a category / categories for each email

public function getItems()
    {
        return $this->hasMany(Categories::className(),['category_id' => 'category_id'])
            ->viaTable('Emailcategories',['email_id' => 'email_id']);
    }

4. As a result, in the GridView, I need to display this in the Categories column (each cell will have at least one category)
Now I can only display the first element:
[
                'attribute' => 'category_id',
                'label' => 'Категория',
                'value' => 'items.0.category',
]

How to parse this items array so that it outputs the corresponding nested element in the corresponding row of the table.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
matperez, 2015-07-06
@Vitalij_D

You can pass an anonymous name to value , and in it you can already form the string you want. Like this:

'value' => function($model) {
 return implode(',', $model->items);
}

V
Vitaliy, 2015-07-06
@Vitalij_D

The function worked:

'value' =>  function($data) {
                    $str ='';
                    foreach($data['items'] as $item)
                    {
                        $str.=$item['category'].',';
                    }
                    return $str;
                },

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question