CakePHP不会为HABTM关系插入关联关联

时间:2012-08-29 11:47:54

标签: cakephp cakephp-2.1 cakephp-2.2

我在CakePHP 2.2.1中有两个模型:

class Episode extends AppModel {
    public $hasAndBelongsToMany = array(
    'Tags' => array('className' => 'Tag')
    );
}

class Tag extends AppModel {
    public $hasAndBelongsToMany = array(
        'Episode' => array('className' => 'Episode')
    );
}

我想同时插入一集和一个标签并将它们相互链接。从我得到的文档中,这将是我在控制器方法中执行的正确代码:

$this->Tag->create();
$this->Tag->save(array(
    'name' => 'Test Tag'
));
$tagid = $this->Tag->getInsertID();

var_dump($tagid); // works

$this->Episode->create();
$this->Episode->save(array(
    'Episode' => array(
        'title' => 'Test with Tag'
    ),
    'Tags' => array(
        'Tag' => array($tagid)
    )
));

我没有收到任何错误消息,并且创建了两个记录,但是episodes_tags表中没有插入行。 CakePHP执行以下查询:

Nr  Query                                                                                                              Err Aff Rws Took (ms)
1   INSERT INTO `pottcast`.`tags` (`name`) VALUES ('Test Tag')                                                              1   1   0
2   INSERT INTO `pottcast`.`episodes` (`title`) VALUES ('Test with Tag')                                                    1   1   0
3   SELECT `EpisodesTag`.`tag_id` FROM `pottcast`.`episodes_tags` AS `EpisodesTag` WHERE `EpisodesTag`.`episode_id` = 9     0   0   0

我做错了什么?

1 个答案:

答案 0 :(得分:0)

试试这个:

在剧集模型中:

public $hasAndBelongsToMany = array(
    'Tag' => array(
        'className' => 'Tag',
        'joinTable' => 'episodes_tags',
        'foreignKey' => 'episode_id',
        'associationForeignKey' => 'tag_id',
        'unique' => 'keepExisting',

    ));

在您的控制器中:

$this->Episode->save(array(
    'Episode' => array(
        'title' => 'Test with Tag'
    ),
    'Tag' => array(
        'Tag' => $tagid
    )
));

询问是否不适合你。