1

Say I have 2 models, Category and POI where 1 Category can have many POIs.

$categoryDetails = Category::with([ 'pois' => function ($query) { $query->where('is_poi_enabled', true); }, ])->findOrFail($id); 

The above query returns results from the specific Category as well as its POIs.

However, with the query below:

$query->select('id', 'name')->where('is_poi_enabled', true); 

The POIs become empty in the collection.

Any idea why this is happening? When added a select clause to the Eloquent ORM?

1
  • 1
    Which is the foreign key user for pois ? Select that foreign key too. Commented Mar 30, 2020 at 3:53

1 Answer 1

2

While doing a select it's required to fetch the Relationship local or Primary key. For an example POIs table contains category_id then it's required to select it Try this:

$categoryDetails = Category::with([ 'pois' => function ($query) { $query->select(['id', 'category_id', 'is_poi_enabled']) ->where('is_poi_enabled', true); }, ])->findOrFail($id); 

Good luck!

Sign up to request clarification or add additional context in comments.

2 Comments

But why is it not required when it's a many-to-many relationship?
It depends if you are using pivot table it's required if your connecting table with primary or local keys it's required.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.