1
votes

I'm trying to make relationship table for products and categories.

This is my Products Model

protected $table = 'products';

    protected $fillable = ['sku', 'slug', 'type'];

    public function category()
    {
        return $this->belongsTo('Modules\Product\Entities\Categories', 'categories_products', 'category_id', 'id');
    }

And this is my Categories model:

protected $table = 'categories';
    
    protected $fillable = ['parent_id', 'name'];


    public function parent()
    {
        return $this->hasOne(self);
    }

    public function products()
    {
        return $this->hasMany('Modules\Product\Entities\Products', 'categories_products', 'product_id', 'id');
    }

Every time when I try to get Products with categories like so:

public function getProducts()
    {
        return Products::with('category')->get();
    }

It's returning that category is null. My relation ship table is called categories_products and it have 2 integers product_id and category_id.

1
just rename table name categories_products to category_product singular term - Kamlesh Paul

1 Answers

1
votes

You should have a belongsTomany relationship in your model.

Product Model

protected $table = 'products';

protected $fillable = ['sku', 'slug', 'type'];

public function categories()
{
    return $this->belongsToMany('Modules\Product\Entities\Categories', 'categories_products', 'product_id', 'category_id');
}

Category model

protected $table = 'categories';

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


public function parent()
{
    return $this->belongsTo('Modules\Product\Entities\Categories','parent_id','id');
}

public function products()
{
    return $this->belongsToMany('Modules\Product\Entities\Product', 'categories_products', 'category_id', 'product_id');
}