HABTM创建所有记录CakePHP

时间:2015-06-12 20:54:57

标签: php sql cakephp has-and-belongs-to-many

数据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 )
)

表格应该在CakePHP中注册三个表格如何描述并仍然正确地关联它们?我尝试了不同的方式而不能。

1 个答案:

答案 0 :(得分:0)

这是一篇关于CakePHP的HABTM的好文章:http://patisserie.keensoftware.com/en/pages/how-to-save-habtm-data-in-cakephp

最重要的是:

关联现有记录:

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

关联新记录:

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

关于组合关联解决方法的文章还有一点。