繁体   English   中英

yii2 - 多对多关系的CRUD

[英]yii2 - CRUD for Many to Many Relations

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

现在我试图在Github问题跟踪stackoverflow跟踪的帮助下手动模拟相同类型的默认CRUD。 我在尝试这个时遇到了以下问题。

问题-1(具有多对多关系的表的模型类):无法初始化类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'],
    ],
]); ?>

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

谢谢

您应该为所有表创建模型。

示例关系

/**
* @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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM