Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent select function cause empty relation

Following is my query

$user = User::select(['uuid','name','about'])->with(['education','work'])->first();

this returns empty data for relationship education and work, but if I remove select function from query I am getting data in relationship and it also returns all columns of user table which I don't want.

how can solve this problem

like image 250
Sharad Kale Avatar asked Feb 04 '23 14:02

Sharad Kale


1 Answers

The problem is that relationships (with(...)) execute an additional query to get the related results. Let's say you have one to many relationship where users have many works. User::with('work')->find(1) will then execute these 2 queries:

select user where id = 1 and select works where user_id = 1.

So basically in order to be able to execute the second query (fetch relationship data) you need to include id (or whichever column you're referencing) in you select statement.

Fix:

$user = User::select(['uuid','name','about', 'id'])->with(['education','work'])->first();

Same principle in different forms applies to all relationships. For example in the inverse of hasMany which is belongsTo you would need to select the foreign key (for example user_id).

like image 183
DevK Avatar answered Feb 08 '23 15:02

DevK