staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Data duplication on hasManyTrough with pivot

psust opened this issue · comments

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.

Hi @psust,

Neither of these worked.

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

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?

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");