Home > Blockchain >  Get nested belongstomany in laravel
Get nested belongstomany in laravel

Time:10-03

Hello I have a question: I have three things :

Top Category Category Product

I want to have this : Top Category -> Category -> Product So I can get all nested information to one Top Category

My Models :

class Overcategory extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'img',
    ];

    public function categories()
    {
        return $this->belongstoMany(Category::class);
    }
}

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
        'category_title',
        'category_description',
        'category_preview_img',
        'over_categories_id',
        'order',
        'price'
    ];

    public function product()
    {
        return $this->belongstoMany(Product::class);
    }

    public function overcategories()
    {
        return $this->belongstoMany(Overcategory::class);
    }
}
class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'product_title',
        'product_desc',
        'product_preview_img',
        'product_price',
    ];

    public function category()
    {
        return $this->belongstoMany(Category::class);
    }
}

And my code to get the Top Category with Category is this :

  $relationsship = Overcategory::with('categories')->get();

How would I get the categories with their product too?

CodePudding user response:

In order to get all Overcategory with their Category and their Product, you can use the dot notation when you eager load the relationships.

$relationsship = Overcategory::with('categories.product')->get();

// will get you all the Overcategories with a Categories relationshiop and inside each Category, the Products will be loaded.

This also works the exact same way when you are working on eloquent collections instead of a query builder, with the load method instead of with.

If you want to read more on this topic, here is the documentation https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence.

Quick note aside, if a relationship returns multiple items (which is the case with product) it should be plural (products).

  • Related