Needed help with relation between cart table and products from product table

I am currently working on ecommerce backend project, can any one tell me how can i show relationship between cart table and products from product table.
A cart can have one cart id but there will be different product id so how can create a table with cart
Please help me with this

this relationship is M2M (many to many), because a cart has many products, and a product can be in multiple carts so you end up with 3 tables:

  1. carts
  2. products
  3. cart_product

both carts and products table need to have an id, and then cart_product should have cart_id and product_id and corresponding foreign key constrains.

3 Likes

Can you tell me table schema or attributes?

I did? Or at least the foreign keys. What other fields you have, that is up to you.

I also told you what you need (M2M), so you can now also find articles which might further explain many to many relationships

1 Like

Yeah! Thanks , i will look into☺️

the 4 essential fields are:

carts.id
products.id
cart_product.cart_id
cart_product.product_id

where cart_id references id on carts and product_id references id on products

those are the 4 essential keys for your join operations.

1 Like

how to implement post route for cart with these

post route? What back-end language are you using? And are you using any frameworks?

you would need to make a route which accepts two things:

id of the cart
id of the product

then you can make a record in the cart_product table. Of course you would need some sanity checks:

cart needs to belong to user
product needs to exists, and in stock.

possible more sanity checks, but where is the fun if I spoil everything?

1 Like

i was actually having problem with “cart needs to belong to user” in express js,
if i create cart how should i make the it belongs to that user or is this done in full stack
as i am doing only backend for now

I have no experience with express JS.

you could give the cart a user_id foreign key. Then on cart creation, store the user_id of the authenticated user on the carts table.

you would need authentication as well, which is mostly back-end.

1 Like