HABTM creating all records CakePHP

83 views Asked by At

data CakePHP:

Array (
    [Table_1] => Array (
        [name] => Test
    )
    [Table_2] => Array (
        [0] => Array (
            [name] => Test
        )
       [1] => Array (
            [name] => Test
        )
    )
)

SQL:

CREATE TABLE Table_1 (
    id INT AUTO_INCREMENT,
    name VARCHAR ( 10 ),
    PRIMARY KEY ( id )
)
CREATE TABLE Table_2 (
    id INT AUTO_INCREMENT,
    name VARCHAR ( 10 ),
    PRIMARY KEY ( id )
)
CREATE TABLE Table_1_2 (
    id INT AUTO_INCREMENT,
    table1_id INT,
    table2_id INT,
    PRIMARY KEY ( id ),
    FOREIGN KEY ( table1_id ) REFERENCES Table_1( id ),
    FOREIGN KEY ( table2_id ) REFERENCES Table_2( id )
)

The form shall register the three tables there described how to do this in CakePHP and still associate them properly? I tried different ways and could not.

1

There are 1 answers

2
Skatch On

Here's a good article on CakePHP's HABTM: http://patisserie.keensoftware.com/en/pages/how-to-save-habtm-data-in-cakephp

Most important:

Associating existing records:

array(
    'Foo' => array(
        'id' => '...',
        ...
    ),
    'Bar' => array(
        'Bar' => array(
            [0] => 'id1', // id of an existing Bar
            [1] => 'id2', // id of another existing Bar
            ...
        )
    )
)

Associating new records:

array(
    [0] => array(
        [Foo] => array(
            [id] => ...
        ),
        [Bar] => array(
            [name] => ...
        )
    ),
    [1] => array(
        [Foo] => array(
            [id] => ...
        ),
        [Bar] => array(
            [name] => ...
            )
        )
)

There's a little more in the article on combined associations workaround.