Laravel Eloquent Relationships速记表

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值