LoginSignup
12
14

More than 5 years have passed since last update.

【Laravel】ポリモーフィックリレーションについて

Posted at

ポリモーフィックリレーションとは

親が複数ある場合のリレーションです。
例えば、コメントテーブルがあって、そのメモはユーザに紐づいているものと、投稿に紐づいているものがあります。
この時、コメントテーブルは1つで両親に紐づけることが可能です。

 テーブル設計

hasMenyのリレーションとかだとコメントテーブルにuser_idとpost_idを作成して各親のidを取得しますが、
今回はcommentable_idとcommentable_typeを用意します。

今後親が増えまくった時に、いちいち◯◯_idカラムを追加すると複雑になってしまいます。
commentable_idには各親のidが入るので、idが被ることもあります。
そこでcommentable_typeにユーザならuser、投稿ならpostと入力することで同じidでも区別することが可能になります。

実装例

まず親。

user.php
public function comments()
    {
        return $this->morphMany('App\Http\Model\Comment', 'commentable');
    }
post.php
public function comments()
    {
        return $this->morphMany('App\Http\Model\Comment', 'commentable');
    }

そして子。

comment.php
public function commentable()
    {
        return $this->morphTo();
    }

これだけで完成です。
あとは$user->comments()->bodyとかすれば値が取得できます。

12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14