staudenmeir / eloquent-has-many-deep

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

hasManyDeep A hasMany B belongsToMany C. need help with setting up relationship `A::with('C')` #239

Closed swapnilsarwe closed 3 months ago

swapnilsarwe commented 3 months ago

I have 3 models named

User -> hasMany -> Post Post -> belongsToMany -> Category Category -> belongsToMany -> Post

Relationship are as follows

class User extends Model {
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }
}

class Post extends Model {
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
    public function categories(): BelongsToMany
    {
        return $this->belongsToMany(Category::class);
    }
}

class Category extends Model {
    public function posts(): BelongsToMany
    {
        return $this->belongsToMany(Post::class);
    }
}

I am looking for the way where I can get all the categories for the user in the following way

User:with('categories')->get();

Its not supported out of the box in the laravel

class User extends Model {
    public function categories(): HasManyThrough
    {
        return $this->hasManyThrough(Category::class, Post::class);
    }
}

I tried the following & it did not work as expected. I was wondering if I am missing something.

class User extends Model {
    public function categories(): HasManyDeep
    {
        return $this->hasManyDeep(Category::class, Post::class);
    }
}

Can anyone help me with this? If you feel this irrelevant, you can close the issue immediately.

staudenmeir commented 3 months ago

Hi @swapnilsarwe, You need to add the pivot table: https://github.com/staudenmeir/eloquent-has-many-deep?tab=readme-ov-file#manytomany

class User extends Model
{
    public function categories(): HasManyDeep
    {
        return $this->hasManyDeep(Category::class, [Post::class, 'category_post']);
    }
}
swapnilsarwe commented 3 months ago

Thanks @staudenmeir . My bad, went through the example but was doing the other way round and never got it working. Appreciate your help.