首页 文章

Yii2迁移中的多对多关系

提问于
浏览
0

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

  • 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生成活动记录类,将自动 Build 关系 . 然后,例如,您可以使用以下语法: $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']);
    }
    

相关问题