staudenmeir / eloquent-has-many-deep

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

Assistance with inverse of belongsToMany through hasMany #57

Closed TheFrankman closed 4 years ago

TheFrankman commented 4 years ago

Hello There,

I'm using your repo to get a relationship, and i'm really struggling using it for the inverse, wondering if you could provide some assistance.

I've attached an image that explains it best. Top digram is the one that's working, bottom is the one i'm yet to figure out

image

To elaborate further this is storage -> playlist which is working (thanks!)

public function playlists(): HasManyDeep
{
    return $this->hasManyDeep(Playlist::class, [Item::class, 'item_playlist']);
}

The above works because storage HasMany items and Items BelongToMany playlists.

The inverse : as playlist belongsToMany items and an item BelongsTo storage.

So I believe what i'm looking for is BelongsTo through belongsToMany ?

staudenmeir commented 4 years ago

For the second relationship, you need to swap the last foreign and local key:

class Playlist extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function storages(): HasManyDeep
    {
        return $this->hasManyDeep(
            Storage::class,
            ['item_playlist', Item::class],
            [null, null, 'id'],
            [null, null, 'storage_id']
        );
    }
}
TheFrankman commented 4 years ago

You sir, are a fantastic human! Works perfectly.

Firstly, thank you for the package. Secondly, thank you for your quick reply!