giozh
giozh

Reputation: 10068

CakePHP: habtm with join table having an extra field

I am generating model tables with cake bake utility, and I am facing a strange situation.

I have these tables:

where product_guest table keep trace of what product a guest bought, and the amount of product bought.

Now, with HABTM relationship on cake bake, I can only specify relation between tables product and guest, but there's no trace of the amount field.

How can I map this situation correctly to retrieve and add amount too?

Upvotes: 0

Views: 472

Answers (2)

Pratik Joshi
Pratik Joshi

Reputation: 11693

Wrong table structure 1st of all

You should have

guests : id , user_name , password 

This is the guest who will purchase product . This is master table.

products : id , product_name , description 

This is your product table with details regarding to products like description etc. This is master table.

orders -> id , amount , user_id

Here order is a table with details such as who bought product and price. This is master table.

Then one order can have many Items so

orders_products ->  order_id , product_id 

Now this will contain order id and which product was included as foreign key. This is Child table which contains Foreign keys of product and order.

Here orders_products is HABTM with products And orders as

One order can contain multiple products.And one product can be part of multiple orders. Does it make sense ?

Upvotes: 0

AgRizzo
AgRizzo

Reputation: 5271

In your case, HABTM is not the correct association to use. You should be using the hasMany through association.

The fundamental change is that you need a third model based on your product_guest table.

Create these relationships:

  • Product hasMany ProductGuest
  • Guest hasMany ProductGuest
  • ProductGuest belongsTo Product
  • ProductGuest belongsTo Guest

Upvotes: 3

Related Questions