嵌套预加载特定列
Nested Eager Loading Specific Columns
当我这样做时
$category = NewsCategory::whereSlug($slug)->with('news.category:id,title,slug')->firstOrFail();
然后我有以下疑问
select * from `news_categories` where `slug` = 'novinki' limit 1
select * from `news_posts` where `news_posts`.`category_id` in (2) and `news_posts`.`deleted_at` is null
select `id`, `title`, `slug` from `news_categories` where `news_categories`.`id` in (2)
但我也想在第一个新闻关系中加载特定的列,如果我这样做会出错
$category = NewsCategory::whereSlug($slug)->with('news:id,title,image.category:id,title,slug')->firstOrFail();
获取此查询的正确方法是什么?
select * from `news_categories` where `slug` = 'novinki' limit 1
select `id`, `title`, `image` from `news_posts` where `news_posts`.`category_id` in (2) and `news_posts`.`deleted_at` is null
select `id`, `title`, `slug` from `news_categories` where `news_categories`.`id` in (2)```
我会将急切加载的关系放入一个数组中
试试这个:
$category = NewsCategory::whereSlug($slug)
->with([
'news:id,title,image,category_id,deleted_at',
'news.category:id,title,slug'
])->firstOrFail();
或者根据我个人的喜好,使用闭包来扩展查询,如下所示:
$category = NewsCategory::whereSlug($slug)
->with([
'news' => function($query){
$query->select('id','title','image','category_id','deleted_at');
},
'news.category' => function($query){
$query->select('id','title','slug');
}
])->firstOrFail();
当我这样做时
$category = NewsCategory::whereSlug($slug)->with('news.category:id,title,slug')->firstOrFail();
然后我有以下疑问
select * from `news_categories` where `slug` = 'novinki' limit 1
select * from `news_posts` where `news_posts`.`category_id` in (2) and `news_posts`.`deleted_at` is null
select `id`, `title`, `slug` from `news_categories` where `news_categories`.`id` in (2)
但我也想在第一个新闻关系中加载特定的列,如果我这样做会出错
$category = NewsCategory::whereSlug($slug)->with('news:id,title,image.category:id,title,slug')->firstOrFail();
获取此查询的正确方法是什么?
select * from `news_categories` where `slug` = 'novinki' limit 1
select `id`, `title`, `image` from `news_posts` where `news_posts`.`category_id` in (2) and `news_posts`.`deleted_at` is null
select `id`, `title`, `slug` from `news_categories` where `news_categories`.`id` in (2)```
我会将急切加载的关系放入一个数组中
试试这个:
$category = NewsCategory::whereSlug($slug)
->with([
'news:id,title,image,category_id,deleted_at',
'news.category:id,title,slug'
])->firstOrFail();
或者根据我个人的喜好,使用闭包来扩展查询,如下所示:
$category = NewsCategory::whereSlug($slug)
->with([
'news' => function($query){
$query->select('id','title','image','category_id','deleted_at');
},
'news.category' => function($query){
$query->select('id','title','slug');
}
])->firstOrFail();