staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

Question: HasMany through ManyToMany and BelongsTo #166

Closed andreinocenti closed 2 years ago

andreinocenti commented 2 years ago

Hello,

I had the below relationship that worked on the previous versions. Right now i just could make it work with hasManyDeepFromRelations. But it does not look I'm doing it right.

I want to get all TagGroups from Posts model. The relationship is: Posts -> ManyToMany (posts_tags) -> Tags -> BelongsTo -> TagGroups

I've tried

 $this->hasManyDeep(TagGroup::class,['posts_tags', Tag::class]);

But no lucky, it looks like "hasManyDeep" tries to do a hasMany relationship from Tag to TagGroup, not a BelongsTo.

Am I missing something?

Thank you

staudenmeir commented 2 years ago

hasManyDeep() doesn't know that the last relationship is a BelongsTo. You need to swap the foreign and local key manually:

$this->hasManyDeep(
    TagGroup::class,
    ['posts_tags', Tag::class],
    [null, null, 'id'],
    [null, null, 'tag_group_id']
);
andreinocenti commented 2 years ago

Jonas, it worked as charm. Thank you very much.

I've read the docs, I could'nt find that I needed to config it like this. Might be interest to add this info/exemple in the docs

Thank you very much!