staudenmeir / eloquent-has-many-deep

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

Need help with self-references in manytomany -> manytomany #162

Closed jaxramus closed 2 years ago

jaxramus commented 2 years ago

I have 2 models/tables:

a user can be a manager or a salesperson

i have 2 pivot tables:

in my lead model, here is my belongstomany for salespeople:

public function salespeople()
{
    return $this->belongsToMany(User::class, 'lead_salespeople', 'lead_id', 'salesperson_id');
}

in my user model, here are my belongstomany for leads, managers, & salespeople:

public function leads()
{
    return $this->belongsToMany(Lead::class, 'lead_salespeople', 'salesperson_id', 'lead_id');
}

public function managers()
{
    return $this->belongsToMany(User::class, 'manager_salespeople', 'salesperson_id', 'manager_id');
}

public function salespeople()
{
    return $this->belongsToMany(User::class, 'manager_salespeople', 'manager_id', 'salesperson_id');
}

i am trying to create a managers relationship in the lead model:

public function managers()
{
    return $this->hasManyDeep(User::class, ['lead_salespeople', User::class, 'manager_salespeople']);
}

this gives me the following error:

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'users' (SQL: select users.*, lead_salespeople.lead_id as laravel_through_key from users inner join manager_salespeople on manager_salespeople.user_id = users.id inner join users on users.id = manager_salespeople.user_id inner join lead_salespeople on lead_salespeople.user_id = users.id where lead_salespeople.lead_id = 1)

i would like to get all the managers for a lead through the salespeople

how do i specify the correct keys and table aliases to use in the hasmanydeep method in this case?

i can't seem to find the docs to specify this given my use case.

jaxramus commented 2 years ago

Holy shit I think I got it:

public function managers()
{
    return $this->hasManyDeepFromRelations($this->salespeople(), (new User)->setAlias('salesperson')->managers());
}

Dude you're a genius. This package is insane.