简体   繁体   中英

Cakephp save extra attribute in HABTM relation

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.

Don't use HABTM

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM