//获取已发布的100条文章
$posts = Post::limit(100)->get(); //一次查询
$authors = array_map(function($post) {
// 对作者模型生成查询
return $post->author->name;
}, $posts);
//获取已发布的100条文章 - 并预加载文章对应作者
$posts = Post::with('author')->limit(100)->get();//2次查询
$authors = array_map(function($post) {
// 对作者模型生成查询
return $post->author->name;//这里讲不在产生查询
}, $posts);
select * from `posts` select * from `authors` where `authors`.`id` in (?, ?, ?, ?, ?) [1,2,3,4,5]
$posts = App\Post::with(['author', 'comments'])->get();
Post -> belongsTo -> Author //每个文章只属于一个用户 Author -> hasMany -> Post //每个用户拥有多个文章 Author -> hasOne -> Profile //每个用户只有一个简介
//获取所有文章 - 并预加载文章对应作者
$posts = App\Post::with('author')->get();//两次查询
//根据每个 `作者` 获取其简介
$posts->map(function ($post) {
//虽然我们直接通过$author = $post->author不会产生查询,
//但当调用$author->profile时,每次都会产生一个新查询
return $post->author->profile;
});
//获取所有文章 - 并预加载文章对应作者及每个作者对应de profile
$posts = App\Post::with('author.profile')->get();//三次查询
$posts->map(function ($post) {
//不在产生新查询
return $post->author->profile;
});
select * from `posts` select * from `authors` where `authors`.`id` in (?, ?, ?, ?, ?) [.....] select * from `profiles` where `profiles`.`author_id` in (?, ?, ?, ?, ?) [.....]
$posts = App\Post::all();//一次查询
$posts->load('author.profile');//两次查询
$posts->map(function ($post) {
//不在产生新查询
return $post->author->profile;
});
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有