2017-06-17 66 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()功能

調用了很多單獨的查詢