whereismydipp
whereismydipp

Reputation: 566

laravel eloquent retrieve part of relationship

Im working on an application using eloquent for retrieving models.

Status

Lets assume I have a model for GROUP,PERSON,HOBBY.

All these are connected 1:n

GROUP 1---n PERSON

PERSON 1---n HOBBY

The approach could be to retrieve the model:

$group = Group::find(123)->with('persons.hobbies')->get();

To display the model in my template I would fire my group to the template. Then I would iterate over my persons in that group and also over my hobbies to for example display the name of the hobby.

Question

As this model is very(!) trivial. I would like to know if it is possible(useless or not) to retrieve directly(not nested) all the hobbies(as an array of Eloquent models). But still the only thing I know is the Group(i.e. groupId) at the beginning?

Thanks in advance

Upvotes: 0

Views: 125

Answers (1)

Glad To Help
Glad To Help

Reputation: 5387

It is not possible because 1---n relationship between group and person could return many person objects for a given group_id . It is not possible to access a list of hobbies of something that is a collection.

If you really want to do this 'directly', my suggestion would be that you use Fluent. the query builder, instead of Eloquent, to join the tables.

Something like:

DB::select('hobby.*')
  ->from('hobby')
  ->join('group', 'group.id = person.group_id')
  ->join('person', 'person.hobby_id = hobby.id')
  ->where('group.id', $group_id);

Upvotes: 1

Related Questions