Reputation: 2301
I have a problem selecting columns (MySQL SELECT statement) with an advanced query::with
statement.
Property::where('public_id', $publicId)->with(['owner' => function ($query) {
$query->select('email'));
}])->first();
The returned owner object is null if I add the select
statement, and the full User
model if I don't add a select('...')
statement.
The queries executed are correct and return the desired data if I run them from phpMyAdmin:
select * from `properties` where `public_id` = '53f1c59cefe65' limit 1;
select `email` from `users` where `users`.`id` in ('54');
Data without select:
{"id":4,"owner_id":54,"owner":{"id":54,"username":"ckertzmann","email":"[email protected]","permissions":[],"activated":true,"activated_at":null,"last_login":null,"first_name":"Daisy","last_name":"Haag","created_at":"2014-08-18 09:21:26","updated_at":"2014-08-18 09:21:26"}}
Data with select:
{"id":4,"owner_id":54,"owner":null}
Upvotes: 0
Views: 85
Reputation: 81187
You need to select the keys so Eloquent knows how to match related models to their respective relation parents.
Property::where('public_id', $publicId)->with(['owner' => function ($query) {
$query->select('email', 'owner_id');
}])->first();
Upvotes: 1