1

when I do this

$category = NewsCategory::whereSlug($slug)->with('news.category:id,title,slug')->firstOrFail(); 

then I have following queries

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) 

but I want to load specific columns on first news relation also and I have error if I do like this

$category = NewsCategory::whereSlug($slug)->with('news:id,title,image.category:id,title,slug')->firstOrFail(); 

what is the correct way to get this query?

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)``` 

1 Answer 1

1

I would put the eager loaded relationships into an array

Try this:

$category = NewsCategory::whereSlug($slug) ->with([ 'news:id,title,image,category_id,deleted_at', 'news.category:id,title,slug' ])->firstOrFail(); 

Or as my personal preference, use closures to expand the query like this:

$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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

using closure it is easy to make where queries 'news' => function($query){ $query->select('title','slug','category_id','image','fulltext','created_at')->whereIsPublished(true); }, 'news.category' => function($query){ $query->select('id','title','slug'); } Is it possible using array? Like that 'news:id,title,image,category_id,deleted_at,is_published=true',
I don't think it's possible but not quite sure since I personally use closure most of the time. You should raise it as a new question so other people can try and answer too :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.