0

I have got two Models in CakePHP 2.2.1:

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

and

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

And I want to insert an Episode and a Tag at the same time and link them to each other. From the documentation I got that this would be the right code which I execute inside a controller method:

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

I get no error message and both records are created, but there is no row inserted into the episodes_tags table. CakePHP does these queries:

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

What did I do wrong?

YMMD
  • 3,730
  • 2
  • 32
  • 43

1 Answers1

0

Try This :

In Episode Model:

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

    ));

In your controller:

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

Ask if not work for you.

Krishna
  • 1,540
  • 2
  • 11
  • 25
  • So did I, but nothing changed. Do you have any other ideas? – YMMD Aug 29 '12 at 12:28
  • Oh, you're right. Indeed it does create the row, but I got confused because it prints it as a `SELECT` in the SQL log. Thank you very much for your help! Do you know the reason why there is no third `INSERT`? – YMMD Aug 29 '12 at 12:38