Hello,
I am doing
$model = new User;
return $model->with(['profile', 'profile.details' => function($q) { $q->select('first_name'); }])->find($id);
If I put anything but 'id' in the $q->select() it returns null for that load. I triple checked the query and it is correct, if I run it, it returns the data I need.
Example without select
{
"id": 1,
"blah": "blahh",
"profile": {
"id": 1,
"test": "test",
"details": {
"id": 1,
"first_name": "test",
"last_name": "testing",
"email": "[email protected]"
}
}
}
example with select
{
"id": 1,
"blah": "blahh",
"profile": {
"id": 1,
"test": "test",
"details": null
}
}
example with select('id')
{
"id": 1,
"blah": "blahh",
"profile": {
"id": 1,
"test": "test",
"details": {
"id": 1
}
}
}
I removed all the extra garbage stuff from the results.
Any idea of what may be going on?
You are probably thinking of eager loading in Laravel as being similar to a SQL join where you can write something like
select foo.*, bar.baz
from foo
join foo.id = bar.id
where you just worry about the fields you want returned in your select and join it later on. However with eager loading there is actually 2 queries being executed, in your example, (without specifying select()):
select * from profile
and
select * from details where id in (1, 2, 3, ...)
where the ids are defined by the results of the first query.
If you specify which fields to select and don't include the foreign keys, (id here), then Eloquent doesn't realise which detail records belong to which profile records and just returns null.
Hopefully I have explained this clearly.
thank you it's useful to know
Most helpful comment
You are probably thinking of eager loading in Laravel as being similar to a SQL join where you can write something like
where you just worry about the fields you want returned in your select and join it later on. However with eager loading there is actually 2 queries being executed, in your example, (without specifying select()):
and
where the ids are defined by the results of the first query.
If you specify which fields to select and don't include the foreign keys, (id here), then Eloquent doesn't realise which detail records belong to which profile records and just returns null.
Hopefully I have explained this clearly.