Yii2迁移中的多对多关系

亚历克斯·利亚申科

我有2张桌子,postcomment在Laravel中,我可以comment_post通过在模型中定义关系来隐式创建数据透视表如何在Yii2中做同样的事情?

表格发布:

  id    -- PK
  text

表如何:

  id    -- PK
  text
  user_id

表comment_post:

  id    -- PK
  post_id   -- foreign key references ID on post table
  comment_id    -- foreign key references ID on comment table
数据技能

假设您有一个名为“ user”的表,其pk为“ id”

从命令行进行以下迁移:

yii migrate/create create_post_table --fields="text:text"
yii migrate/create create_comment_table --fields="text:text,user_id:integer:notNull:foreignKey(user)"
yii migrate/create create_postComment_table --fields="post_id:integer:notNull:foreignKey(post),comment_id:integer:notNull:foreignKey(comment)"

然后运行:

yii migrate

然后使用gii生成活动记录类,将自动建立关系。然后,例如,您可以使用以下语法:$post->comments

有关迁移的更多信息:http : //www.yiiframework.com/doc-2.0/guide-db-migrations.html

由于评论而更新:

为了简化$post->comments语法,在Post类内部,您将具有以下功能:

public function getComments()
{
    return $this->hasMany(Comment::classname(),['id'=>'comment_id'])
    ->viaTable('postComment',['post_id','id']);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章