staudenmeir / eloquent-has-many-deep

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

problem when perform where on "hasManyDeep" relation #52

Closed dpetrovaliev closed 4 years ago

dpetrovaliev commented 4 years ago

Hi, i was really impressed by this package until i had to perform a where query on hasManyDeep relation.

here is my tables:

User -id -name ...

Company -id -name ...

Users_Companies -company_id -user_id

Venues -id -name -company_id ...

My User model has this relation:

    public function venues()
    {
        return $this->hasManyDeep(Venue::class, ['users_companies', Company::class]);
    }

When i run this query:

    public function isPartOfVenue(Venue $venue)
    {
        return $this->venues()->where('id', $venue->id)->exists();
    }

I'm receiving an error:

Illuminate\Database\QueryException: SQLSTATE[42702]: Ambiguous column: 7 ERROR: column reference "id" is ambiguous LINE 1: ..."."id" where "users_companies"."user_id" = $1 and "id" = $2)... ^ (SQL: select exists(select * from "venues" inner join "companies" on "companies"."id" = "venues"."company_id" inner join "users_companies" on "users_companies"."company_id" = "companies"."id" where "users_companies"."user_id" = 1 and "id" = 9) as "exists") in file /Users/danielpetrovaliev/Code/edenallmvp/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 665

staudenmeir commented 4 years ago

The query contains multiple id columns and the database doesn't know which one you are referring to.

You need to provide the table name:

public function isPartOfVenue(Venue $venue)
{
    return $this->venues()->where('venues.id', $venue->id)->exists();
}
dpetrovaliev commented 4 years ago

Is there a way when you know type of relation and related object(in my case 'venues') to append table name to all where params ?

staudenmeir commented 4 years ago

You could implement such a solution, but it wouldn't be a one-liner. IMO, it's much easier to provide the table name yourself.