Select certain properties on ::with
Pregunta
I have a members table with a lot of data. I want to view a list of "Alarms" with the member's name included, but no other information about that member.
I am currently using
Alarm::with('member')->get();
which returns all the alarm data and all the member data associated with member_id.
What I want is to specify the "member" data to only return "name" and nothing else from member.
This could normally be done with
Member::select('name')->get();
but I'd like to know how to achieve that result through eager loading without having to edit the model and add to the "hidden" since I'll be needing the data in other calls.
Solución
Alarm::with(['member' => function ($q) {
$q->select('id', 'name');
}])->get();
A few things to consider:
select
won't work forbelongsToMany
(many-to-many) relation like above, since it's bugged.- You need to select
primary key
/foreign key
(depending on the relation) in order to let Eloquent match related models to their respective parents - If you want to output data through some kind of JSON api, I suggest using transformers instead - for example fractal
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow