Yii2迁移中的多对多关系

Yii2迁移中的多对多关系,yii2,migration,many-to-many,relation,Yii2,Migration,Many To Many,Relation,我有两个表,post和comment。在Laravel中,我可以通过在模型中定义关系隐式地创建透视表comment\u post。我怎样才能在Yii2中做同样的事情 表柱: id -- PK text 表注释: id -- PK text user_id 表2.评论和帖子: id -- PK post_id -- foreign key references ID on post table comment_id -- foreig

我有两个表,
post
comment
。在Laravel中,我可以通过在模型中定义关系隐式地创建透视表
comment\u post
。我怎样才能在Yii2中做同样的事情

表柱:

  id    -- PK
  text
表注释:

  id    -- PK
  text
  user_id
表2.评论和帖子:

  id    -- PK
  post_id   -- foreign key references ID on post table
  comment_id    -- foreign key references ID on comment table

假设您有一个名为“user”的表,其主键为“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
然后使用生成活动记录类,将自动建立关系。 然后,例如,您可以使用以下语法:
$post->comments

有关迁移的更多信息:

由于评论而更新:

为了方便使用
$post->comments
语法,在post类中,您可以使用如下函数:

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

您需要创建表
comment\u post
和@insaeskull这是否意味着Yii2不能隐式创建透视表?您是说
有很多关系吗?Yii2 Gii可以在创建模型时生成关系。现在我无法使用Gii。有没有办法在没有gii的情况下建立关系?