LoginSignup
5
3

More than 5 years have passed since last update.

eloquentのrelationships定義の備忘録

Posted at

Eloquent:リレーション 5.1 Laravelに全て書かれていることですが結構忘れがちなので、wordpressのtableをeloquentで操作できるようにしたついでに

まとめ

  • 現modelに、他modelのkeyのcloumnがある場合は belongsTo
  • 現modelのkeyの値を持つ他modelへは hasOnehasMany
  • 中間tableを経由したrelationshipsは belongsToMany
  • hasManyなmodelを経由してのrelationshipsは hasManyThrough
  • 動的に依存先を変えたい場合は morphManymorphManymorphedByMany を使う

wordpressのpostsで考えてみる

データベース構造 - WordPress Codex 日本語版にER図があります
postsを中心にusers、comments、termsなどがrelationしていますね

  • postmetaのpost_idで参照され
  • post_authorでusersを参照し
  • commentsのcomment_post_idで参照され
  • term_relationshipsを挟んでterm_taxonomyと繋がってる

コードにするとこんな感じ

use Illuminate\Database\Eloquent\Model;

class Post extends Model {
    protected $primaryKey = 'ID';

    public function metas(){
        return $this->hasMany('PostMeta');
    }
    public function user(){
        return $this->belongsTo('User', 'post_author');
    }
    public function comments(){
        return $this->hasMany('Comment', 'comment_post_id');
    }
    public function term_taxonomies(){
        return $this->belongsToMany('TermTaxonomy', 'term_relationships', 'object_id', 'term_taxonomy_id');
    }
}
5
3
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
5
3