2017-06-17 72 views
0

我有主表和几个子表。yii2连接表中的GridView

主表产品的productID/productNameID/productColorID

和子表

产品名称productNameID /名称

productColorproductColorID /名称

在主表中,我只是插入子表的ID。 并获得正常的名称,而不是我的ID使用功能的产品型号:

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

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

如果我在视图中使用的唯一模式,我可以写$model->productName['name']从子表得到的名字。

但我想创建GridView控件。为此我从Gii创建了默认的CRUD。正如你所知道的GridView使用SearchModel。 当我在列表中做到这一点时,我只有主表中的ID。可能是因为SearchModel中没有自定义函数 我的意思是现在没有连接存储名称的子表的连接。 那么如何将我的主表连接到GridView中的子表?应该怎样做才能做到这一点?

回答

1

有这样做的几种方法: 第一种是最简单的(我认为),你可以写你的关系的名称,然后访问该属性你需要显示在短短的一个字符串:

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

     'productName.name', // Here it is 

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

另一种方法(和更动态的),你可以调用一个匿名函数来显示所需数值如下:

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

关于这些方面的属性应用搜索你可以学到更多Yiiframwork文档中Yii 2.0: Displaying, Sorting and Filtering Model Relations on a GridView

而且除了确保你渴望的负载相关表格,让你的GridView不会使用$model->with()$model->joinWith()功能

调用了很多单独的查询