Product and Category relation in Database?

Hello.
I am lost whileI am working on database design. So I need your help. :slight_smile:

It might be simple but I can’t figure it out.
What I want to do is Product and Category relation
Product has 1 category.
Category has many products.

So I can do like this

product = Repo.one(from p in Product, preload: [:category])
product.category.name

query = from p in Product,
  join: c in Category,
  on: c.name == "Food",
  select: p

So I can get products that has “Food” category.

Which relation should I use?
one to many?

Yes, one to many with Product holding a category_id field.

Product belongs_to :category, Category...
Category has_many :products, Product...

But your join is not functional, maybe like this (not tested)

query = from p in Product,
  join: c in Category,
  on: p.category_id == c.id, 
  where: c.name == "Food",
  select: p
2 Likes

Thanks!