Reputation: 471
I have three Models Theme, Color and ThemeColor (that maps themes available with different colors)
Structured like:
Theme (id, name, properties, image)
Color (id, name, code, image)
ThemeColor (theme_id, color_id, preview); // eg. preview => x theme with a,b,c colors and their related image //
I have baked all these Models, Controllers and Views,
Everything is working well except I am not able to save the [preview] image in ThemeColor Model.
Its related with hasAndBelongToMany.
Array
(
[Theme] => Array
(
[name] => Black and blue
[theme] => black-blue
[description] =>
[status] => 1
[thumb] => Array
(
[name] => Koala.jpg
[type] => image/jpeg
[tmp_name] => F:\Xampp\tmp\phpEBE7.tmp
[error] => 0
[size] => 780831
)
)
[Color] => Array
(
[Color] => Array
(
[0] => 1
)
[Preview] => Array
(
[0] => test.png
)
)
)
I have tried saveAll() but that did not work. Is it possible what I am tring to achieve or I will have to just do it manually.
Please guide.
Upvotes: 2
Views: 1643
Reputation: 66237
The simplest way to handle has-and-belongs-to-many relations with extra attributes is to obey this rule:
When a link table has more than 2 fields: make it a model
That means convert this relation:
Theme <-habtm-> Color
Into:
Theme <-hasmany- ThemeColor
ThemeColor -belongsTo-> Color
ThemeColor -belongsTo-> Theme
This gives you more control, and simpler code/logic. It's still possible to use a habtm relation when it suits you, and not when it doesn't.
The data structure when saving would then be:
array(
'Theme' => array(...),
'ThemeColor' => array(
array('color_id' => x, 'preview' => y),
...
)
)
There's more detailed notes on this in the documentation.
Upvotes: 4