Eloquent Relationships速记表
模型关联中有个大坑:belongsTo反向关联的时候,外键是按照方法名加_id自动寻找的。除此之外的关联,是根据模型名加_id作为外键。
type | define | inverse | remark |
One to One | hasOne | belongsTo |
withDefault() Define default foreign key →based on the model name Inverse default foreign key → name of the relationship method and suffixing the method name with _id |
One to Many | hasMany | belongsTo |
Define default foreign key →based on the
model name Inverse default foreign key → name of the relationship method and suffixing the method name with _id |
Many to Many | belongsToMany | belongsToMany |
Requires intermediate table. withPivot('column1', 'column2'); withTimestamps(); as('subscription')→withTimestamps(); wherePivot('approved', 1) wherePivotIn('priority', [1, 2]); using('App\UserRole'); |
Has Many Through | hasManyThrough | hasManyThrough('App\Post', 'App\User'); | |
Polymorphic | morphMany | morphTo |
morphMany('App\Comment', 'commentable') $comment = App\Comment::find(1); $commentable = $comment→commentable; ↑ Will return either a Post or Video instance, depending on which type of model owns the comment MorphMap |
Many to Many Polymorphic | morphToMany | morphedByMany |
morphToMany('App\Tag', 'taggable'); morphedByMany('App\Post', 'taggable'); |