1

I have main table and several sub tables.

Main table Product : productID / productNameID / productColorID

and subtables

productName : productNameID / name

productColor : productColorID / name

In main table I just insert IDs of sub tables. And to get normal names instead of IDs I use functions in product Model:

public function getProductName()
{
    return $this->hasOne(ProductName::className(), ['nameID' => 'productNameID']);
}

public function getProductColor()
{
    return $this->hasOne(ProductColor::className(), ['colorID' => 'productColorID']);
}

If I use only model in view I can write $model->productName['name'] to get name from subtable.

But I want to create GridView. For this I created default CRUD from Gii. As you know GridView uses SearchModel. When I did this in list I've got only IDs from main Table. probably because there were no custom functions in SearchModel I mean there are no connections now with subtables where names are stored. So how can I connect my main table to subtables in GridView ? What Should be done to accomplish this ?

David
  • 4,332
  • 13
  • 54
  • 93

1 Answers1

2

There are several ways of doing it: First one is the easiest (I suggest), you can write the name of your relation, and then access to the attribute you need to display in just one string:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        'id',

        'productName.name', // Here it is

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

Another way (and more dynamic) you can call an anonymous function to show the desired value as follow:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        'id',

        [
            'attribute' => 'category_id',
            'value' => function (Product $product) {
                return $product->category->name;
                // make sure your model has productName, or it will throw Non-object exception
                // return $product->category ? $product->category->name : null; 
            },
        ],

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

About applying search on those related attributes you can learn more in Yiiframwork documentation Yii 2.0: Displaying, Sorting and Filtering Model Relations on a GridView

And in addition make sure you eager load related tables, so that your gridview won't call a lot of separate queries by using $model->with() and $model->joinWith() functions

Yerke
  • 2,187
  • 3
  • 19
  • 33