drewdan
4 weeks ago
138
5
Laravel

Products related to Categories, but how

Posted 4 weeks ago by drewdan

Hi Guys,

I am a little confused and although I am sure there is an answer on Google, but I do not know how to work my question, so cannot find it.

I had products and categories in my database. I would like to be able to associate the product with many categories. So for example, Chocolates could be in both the Valentines Gifts and Birthday Gift category.

What I did initially was make a ProductCategory model, which stores the product id and category id, then had a relation to both the product and category, but doing it this way meant I would do something like

$category->productCategory->products

Which is ok, but I feel like I should be able to have a relationship which just lets me do:

$category->products

Is this a thing? I figure it would have something to do with hasManyThrough, but, I cannot seem to get this to work.

Any advice would be great! Thanks All!

Please sign in or create an account to participate in this conversation.