Alex Lyashenko
Alex Lyashenko

Reputation: 23

Many-to-many relation in Yii2 migration

I have 2 tables, post and comment. In Laravel I can create pivot table comment_post implicitly by defining relations in models. How can I do the same in Yii2?

table post:

  id    -- PK
  text

table comment:

  id    -- PK
  text
  user_id

table comment_post:

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

Upvotes: 2

Views: 2268

Answers (1)

dataskills
dataskills

Reputation: 656

Assuming you have a table called "user" with pk called "id"

From commandline make the following migrations:

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)"

Then run:

yii migrate

Then use gii to generate the active record classes, the relationships will be made automatically. Then, for example, you can use the following syntax: $post->comments

More on migrations: http://www.yiiframework.com/doc-2.0/guide-db-migrations.html

Update because of comment:

To facilitate the $post->comments syntax, inside your Post class you would have a function like the following:

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

Upvotes: 6

Related Questions