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 ?
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:
Another way (and more dynamic) you can call an anonymous function to show the desired value as follow:
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