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.

有帮助吗?

解决方案

Alarm::with(['member' => function ($q) {
  $q->select('id', 'name');
}])->get();

A few things to consider:

  1. select won't work for belongsToMany (many-to-many) relation like above, since it's bugged.
  2. You need to select primary key / foreign key (depending on the relation) in order to let Eloquent match related models to their respective parents
  3. If you want to output data through some kind of JSON api, I suggest using transformers instead - for example fractal
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top