Laravel Eloquent with() selecting specific column doesn't return results

NewbieCoder

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?

Gautam Patadiya

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!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related