2

I'm working on an Online Store project with Laravel 5.8 and in this project, I wanted to add "Add to favourites" ability for users to add a product to their favourite list.

So I created a Model like this:

class FavouriteProduct extends Model
{
    protected $table = 'favourite_products';
    protected $fillable = ['user_id','product_id'];
}

Now I wonder what are the relationship between this Model with User Model & Product Model and how to apply them.

Basically it looks like Many To Many Relationship. But as I know a Many To Many Relationship comes with a pivot table also and I don't have that.

So can I apply Many To Many Relationship in this case ?

yetep93258
  • 33
  • 1
  • 13
  • You don't need a pivot table. Your User -> FavoriteProducts relation is a one-to-many, FaveriteProduct -> Product a one-to-one relation. Additionally you can use hasManyThrough to directly access the products. – Gert B. Feb 01 '22 at 07:37
  • 2
    You could still aply many-to-many, you will need to set the keys manually because your model and table won't fit the naming convention of Laravel (product_user). In my opinion this is a standard case for many-to-many @GertB., I am not sure why you don't see it like that. User->FavoritePorduct one-to-many and Product->FavoriteProduct one-to-many, this makes it in my opionion a many-to-many. – Aless55 Feb 01 '22 at 07:39
  • 2
    @Aless55 I agree, if the favorite_products model doesn't have extra fields. Since it is a separate model I went for the one-to-many. If it is a many to many, the Model is not really needed. – Gert B. Feb 01 '22 at 07:47

0 Answers0