Eloquent:リレーション 5.1 Laravelに全て書かれていることですが結構忘れがちなので、wordpressのtableをeloquentで操作できるようにしたついでに
まとめ
- 現modelに、他modelのkeyのcloumnがある場合は
belongsTo
- 現modelのkeyの値を持つ他modelへは
hasOne
、hasMany
- 中間tableを経由したrelationshipsは
belongsToMany
- hasManyなmodelを経由してのrelationshipsは
hasManyThrough
- 動的に依存先を変えたい場合は
morphMany
、morphMany
、morphedByMany
を使う
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');
}
}