Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@atomita

eloquentのrelationships定義の備忘録

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');
    }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
3
Help us understand the problem. What are the problem?