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'); |
本文提供了Laravel框架中Eloquent ORM各种模型关联的快速查阅表,包括一对一、一对多、多对多等关联方式及其逆向关联定义。还介绍了如何在多态关联中使用中间表及其它相关操作。
164

被折叠的 条评论
为什么被折叠?



