staudenmeir / belongs-to-through

Laravel Eloquent BelongsToThrough relationships
MIT License
1.15k stars 88 forks source link

hasManyThrough - depth? #18

Closed judgej closed 8 years ago

judgej commented 8 years ago

The belongsToThrough() can set up a relationship to an arbitrary depth. That is really great and useful.

The core eloquent hasManyThrough() only works to a depth of one, which is not so useful when you have a deep relationship to pull out of the database. Would you consider adding a hasManyThroughDeep() method to supplement what eloquent supports?

judgej commented 8 years ago

I can do an equivalent to a hasManyThrough() using joins, so have a workaround. The problem is the joins are done outside of the model and mess around with the details of the query, instead of being a nice abstraction.

Given:

Show --< Group --< Judge --< Class

I want to get all classes for a show:

            $show = Show::find($my_show_id);

            $collection = Class::join('judges', 'classes.judge_id', '=', 'judges.id')
                ->join('groups', 'judges.group_id', '=', 'groups.id')
                ->where('groups.show_id', $show->id)
                ->select('classes.*') // Important to knock out columns from other tables
                ->get();

So that gives me a collection of classes for a show. It does it in one database hit, and being a query, it means I can add additional WHERE clause conditions to the classes.

Ideally, what I would want to do instead is:

$collection = $show->classes;
// or
$collection = $show->classes()->where(...whatever...)->get();
znck commented 8 years ago

Sure. Will do that as a part of plug

judgej commented 8 years ago

Nice. Will have a play with that.

staudenmeir commented 5 years ago

I've created a package for this: https://packagist.org/packages/staudenmeir/eloquent-has-many-deep