Laravel 中的模型关联为我们使用带来了极大遍历,今天总结一下几种常见的模式和用法。
一对多
举例说明,Post ↔ Comment
执行 SQL 数量
如果使用 with 时,会一个查询会拆解为两个 SQL,一个是查找 Post,一个是查找 Comment (该查找使用的是 select in 方法,多个 Post 只执行一次 Comment 的查询工作)
用法(使用 with )
$comments = Post::with('comments')->find(1)->comments
用法(使用 load )
$post = Post::find(1)
$post->load('comments')
load 是对已经查出的模型使用,with 是直接做好关联关系的查询,两者查询的 sql 是一样的 。
多对多
举例说明,User``` ↔ ```Role
用法(使用 with )
$roles = User::with('roles')->find(1)->roles;
用法(使用 load )
$user = User::find(1);
$user->load('roles');
load 是对已经查出的模型使用,with 是直接做好关联关系的查询,两者查询的 sql 是一样的 。
一对一
举例说明,User ↔ Profile
用法(使用 with )
$user = User::with('profile')
以下是回复内容:
采集网址: https://modstart.com/thread/837 |