staudenmeir / eloquent-has-many-deep

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

Data duplication on hasManyTrough with pivot #205

Closed psust closed 1 year ago

psust commented 1 year ago

I have a

persons table and a properties table. They have a many to many relationship. So I have a table person_property.

Person::class belongs to User::class which belongs to Tenant::class.

How would you get all the properties of a Tenant ?

I tried:

<?php

return $this->hasManyDeep(Property::class, [User::class, Person::class, "person_property"]);

But this returns me duplicate properties since I have a many to many relationship.

I tried appending to the relationship: ( like stated in #2 )

<?php

->distinct("properties.id")

# I also tried

->groupBy("properties.id")

Neither of these worked.

I tried using a query instead of a relationship, but I faced the same problem of duplication.

staudenmeir commented 1 year ago

Hi @psust,

Neither of these worked.

Are the queries failing with an error or are the duplicate (just) not getting removed?

Robert-Smagge commented 1 year ago

We also had some trouble with data duplication, encountering this error:

Illuminate\Database\QueryException: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #... of SELECT list is not in GROUP BY clause and contains nonaggregated column ... which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

We solved it by adding 'laravel_through_key' to the offending ->groupBy. Would that solve your issue as well?

psust commented 1 year ago

Hey, sorry I forgot about this. I believe the duplication issue came from a problem with our database.

Anyway I have this now and it seems to work:

<?php

return $this->hasManyDeep(Property::class, [User::class, Person::class, "person_property"])
    ->distinct("properties.id");