Yii2迁移中的多对多关系

时间:2018-01-04 10:43:00

标签: yii2 migration many-to-many relation

我有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

1 个答案:

答案 0 :(得分:2)

假设您有一个名为" 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']);
}