Help us understand the problem. What is going on with this article?

eloquentのrelationships定義の備忘録

More than 3 years have passed since last update.

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');
    }
}
atomita
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした