josoroma
josoroma

Reputation: 1905

HABTM join table with a HABTM relationship

If i have the following database table names in a HTBTM relantionship:

**dressess**
id

**dressess_categories**
id
dress_id
category_id

**categories**
id

How do I have to create the database table names for an HABTM relationship need it in dressess_categories table, for example:

**dressess_categories**
id

**colors_dress_categories**   <--- It is named right?
id
dress_category_id   <--- It is named right?
color_id

**colors**
id

Thanks in advance.

Upvotes: 1

Views: 1169

Answers (1)

Stephen
Stephen

Reputation: 18964

First, the join table needs to have the model names in alphabetical order for CakePHP to recognize them automagically:

dresses_categories /* incorrect */
categories_dresses /* correct */

Now for the problem at hand: If I understand your question correctly, you are trying to create a HABTM association between a Color model and the join table that is used for a different HABTM relationship? This is not possible. (or if it is, it will be a cake-hack-a-thon).

First, stop thinking of relationships as they relate between database tables. Relationships are defined between CakePHP Models, and the tables drive them. What you will need to do in order to accomplish this task is make four models:

Dress
Category
DressCategory
Color

Define relationships like so:

Dress         -> hasMany   -> DressCategory
Category      -> hasMany   -> DressCategory
DressCategory -> belongsTo -> Category, Dress
DressCategory -> HABTM     -> Color
Color         -> HABTM     -> DressCategory

And five tables with the appropriate foreign keys:

dresses
-------
id

categories
----------
id

dress_categories
----------------
id
dress_id
category_id

colors
------
id

colors_dress_categories
-----------------------
id
color_id
dress_category_id

Upvotes: 1

Related Questions