【问题标题】:yii2 - CRUD for Many to Many Relationsyii2 - 多对多关系的 CRUD
【发布时间】:2015-07-02 20:35:45
【问题描述】:

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

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

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

我还想知道是否需要为具有多对多关系的表创建一个模型类来处理 CRUD。

谢谢

【问题讨论】:

    标签: php gridview yii yii2


    【解决方案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,
    ]);
    

    在您的情况下,您可以将 hasOne 替换为 hasMany。

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

    【讨论】:

    • 感谢您的回复。这对我来说非常有效(提供的链接非常有帮助),但我对 joinWith() 中给出的表名的命名约定有疑问。现在它是这样工作的,如果实际的表名是 'table_abc' 那么 yii 调试器会提示将名称命名为 'tableAbc' 为什么会这样?
    • 在配置文件中设置 tablePrefix。它会解决你的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    相关资源
    最近更新 更多