我有2个表, post
和 comment
. 在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 回答
假设你有一个名为“user”的表,其中pk称为“id”
从命令行进行以下迁移:
然后运行:
然后使用gii生成活动记录类,将自动 Build 关系 . 然后,例如,您可以使用以下语法:
$post->comments
有关迁移的更多信息:http://www.yiiframework.com/doc-2.0/guide-db-migrations.html
因评论而更新:
为了方便
$post->comments
语法,在Post类中,您将拥有如下函数: