Cakephp保存HABTM关系中的额外属性 [英] Cakephp save extra attribute in HABTM relation
问题描述
我有三个模型Theme,Color和ThemeColor(用不同颜色来映射主题)
I have three Models Theme, Color and ThemeColor (that maps themes available with different colors)
结构化:
主题(ID,名称,属性,图片)
Theme (id, name, properties, image)
颜色(ID,名称,代码,图片)
Color (id, name, code, image)
ThemeColor(theme_id,color_id,preview); // eg。 preview => x theme with a,b,c colors and their related 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,
除了我无法保存ThemeColor模型中的[预览]图像之外,一切都很好。
Everything is working well except I am not able to save the [preview] image in ThemeColor Model.
它与hasAndBelongToMany相关。 / p>
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
)
)
)
我试过saveAll()但是没有工作。
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.
请指导。
推荐答案
不要使用HABTM
最简单的方法是处理带有额外属性是遵守这条规则:
Don't use HABTM
The simplest way to handle has-and-belongs-to-many relations with extra attributes is to obey this rule:
当链接表有超过2个字段时:使它成为一个模型
When a link table has more than 2 fields: make it a model
这意味着转换这种关系:
That means convert this relation:
Theme <-habtm-> Color
进入:
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),
...
)
)
这篇关于Cakephp保存HABTM关系中的额外属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!