Yii2迁移中的多对多关系

Ale*_*nko 2 migration many-to-many relation yii2

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

桌柱:

  id    -- PK
  text
Run Code Online (Sandbox Code Playgroud)

表评论:

  id    -- PK
  text
  user_id
Run Code Online (Sandbox Code Playgroud)

表comment_post:

  id    -- PK
  post_id   -- foreign key references ID on post table
  comment_id    -- foreign key references ID on comment table
Run Code Online (Sandbox Code Playgroud)

dat*_*lls 5

假设您有一个名为“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)"
Run Code Online (Sandbox Code Playgroud)

然后运行:

yii migrate
Run Code Online (Sandbox Code Playgroud)

然后使用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']);
}
Run Code Online (Sandbox Code Playgroud)