gpt4 book ai didi

php - yii2 - 多对多关系的 CRUD

转载 作者:行者123 更新时间:2023-12-02 01:11:01 25 4
gpt4 key购买 nike

我是 yii 的新手。我自己尝试过,谷歌搜索,发现 yii2 默认 CRUD 生成器 Gii 不会为具有多对多关系的表生成 CRUD。还发现 yii 通过一对多实现了(不是 Gii 意义上的)多对多 yiiDrills .

现在我尝试在 Github issue trail 的帮助下手动模拟相同类型的默认 CRUD和 stackoverflow trail 。我在尝试此操作时遇到以下问题。

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

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

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

我还想知道是否需要为具有多对多关系的表创建一个模型类来处理 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,
]);

您可以根据您的情况将 hasOne 替换为 hasMany。

请检查链接http://www.yiiframework.com/wiki/653/displaying-sorting-and-filtering-model-relations-on-a-gridview/

关于php - yii2 - 多对多关系的 CRUD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31194183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com