staudenmeir / eloquent-has-many-deep

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

Struggling with hasOneDeep #61

Closed TheFrankman closed 4 years ago

TheFrankman commented 4 years ago

Hello there.

Not an Issue, just can't find the correct combination of relationships.

In my system an organisation hasMany customers, a customer hasMany users. I can get the users for an organisation using the following :

// App/Organisation
public function users(): HasManyDeep
    {
        return $this->hasManyDeep(User::class, [Customer::class, 'customer_user']);
    }

The inverse of this relationship is proving difficult. I'm trying to get the organisation for a user.

user hasMany customers customer belongsTo organisation BUT all of a users customers belong to the same organisation so it will need some kind of ->first() on there as well i imagine...

I could obviously just have the organisation_id stored against the user, but If I can get the relationship working it's an arbitrary field as it would never change.

Table structure

user
 - id

customer
 - id
 - organisation_id

customer_user
 - user_id
 - customer_id

organisation
 - id
TheFrankman commented 4 years ago

Don't worry, i got there. The solution is :

    public function organisation(): HasOneDeep
    {
        return $this->hasOneDeep(
            Organisation::class,
            ['customer_user', Customer::class],
            [null, null, 'id'],
            [null, null, 'organisation_id'],
        )->latest('organisations.created_at');
    }