2015-07-02 78 views
2

我是yii的新手。我嘗試過自己,Google搜索,發現yii2默認CRUD生成器Gii不會爲具有多對多關係的表生成CRUD。還發現yii通過一對多達到(不在Gii中)多對多yiiDrillsyii2 - 多對多關係的CRUD

現在我試圖在Github issue trailstackoverflow trail的幫助下手動模擬相同類型的默認CRUD。我在嘗試這個時遇到以下問題。

問題-1(Model類的表有多對多關係):無法初始化類ActiveDataProvider,

$query = TableA::find(); 
    $dataProvider = new ActiveDataProvider([ 
     'query' => $query->TableB(), 
    ]); 

問題-2(查看):即使我能初始化如何通過GridView的

使其
<?= GridView::widget([ 
    'dataProvider' => $dataProvider, 
    'filterModel' => $searchModel, 
    'columns' => [ 
     ['class' => 'yii\grid\SerialColumn'], 
    //How to give the column names like we give for one to many 
    /* Example */ 
     'TableA.attr1', 
     ['class' => 'yii\grid\ActionColumn'], 
    ], 
]); ?> 

而且我想如果需要創建表模型類多對多的關係來處理CRUD就知道了。

感謝

回答

-1

你應該創建的所有錶款。

例關係

/** 
* @return \yii\db\ActiveQuery 
*/ 
public function getCountry() 
{ 
    return $this->hasOne(Country::className(), ['id' => 'country_id']); 
} 

/** 
* @return \yii\db\ActiveQuery 
*/ 
public function getCity() 
{ 
    return $this->hasOne(City::className(), ['id' => 'city_id']); 
} 

例 「搜索」 的方法

$query = Tour::find(); 
// Important: lets join the query with our previously mentioned relations 
// I do not make any other configuration like aliases or whatever, feel free 
// to investigate that your self 
$query->joinWith(['city', 'country']); 

$dataProvider = new ActiveDataProvider([ 
    'query' => $query, 
]); 

你可以在你的情況與替換的hasMany hasOne。

請檢查鏈接http://www.yiiframework.com/wiki/653/displaying-sorting-and-filtering-model-relations-on-a-gridview/

+0

感謝您的回覆。這完全適用於我(鏈接提供了非常有用的),但我有一個懷疑與joinWith()給出的表名的命名約定。現在它是這樣工作的,如果實際的表名是'table_abc',那麼yii調試器會提示'tableAbc'爲什麼會這樣? –

+0

在你的配置文件中設置tablePrefix。它會解決你的問題 –