0

我在 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

我做错什么了?

4

1 回答 1

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
    )
));

询问是否不适合您。

于 2012-08-29T12:13:00.850 回答