yii2 - 多对多关系的CRUD

时间:2015-07-02 20:35:45

标签: php gridview yii yii2

我是yii的新手。我试过自己,用Google搜索并发现yii2默认的CRUD生成器Gii不会为具有多对多关系的表生成CRUD。还发现yii通过一对多({3}}实现了(不是Gii意义上的)多对多。{/ p>

现在,我尝试在yiiDrillsGithub issue trail的帮助下手动模拟相同类型的默认CRUD。我在尝试这个时遇到了以下问题。

Issue-1(具有多对多关系的表的模型类):无法初始化类ActiveDataProvider,

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

Issue-2(View):即使我能够初始化它如何通过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'],
    ],
]); ?>

此外,我想知道是否需要为具有多对多关系的表创建一个Model类来处理CRUD。

由于

1 个答案:

答案 0 :(得分:-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']);
}

示例&#34;搜索&#34;方法

$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。

请查看链接hash

相关问题