0

Might be a newbie question as I'm trying to see what all these "PHP frameworks" are at my free time.

For starters I want to add multiple tags to multiple photos. I have a tags model and mot model (the photos). Snip of mot model:

var $hasAndBelongsToMany = array(
                                    'Tag' =>
                                    array(
                                        'className'              => 'Tag',
                                        'joinTable'              => 'mots_tags',
                                        'foreignKey'             => 'mot_id',
                                        'associationForeignKey'  => 'tag_id',
                                        'unique'                 => false
                                    )
                                );

In my tags controller in add() I have:

$this->Tag->save($this->data);

When print_r'ing $this->data I see:

Array

( [Mot] => Array ( [id] => 2 )

[Tag] => Array
    (
        [title] => 21e21e
    )

)

Tag get inserted into Tags table, but nothing gets inserted into mottags(theres underscore between mot and tag but it italics when i write it here instead of becoming an underscore) table. My mots_tags db schema: (sqlite)

create table mots_tags (id INTEGER PRIMARY KEY, mot_id INTEGER, tag_id INTEGER)

Any clues why Cake writes only to Tags table and not to associacions table? I don't get any SQL errors. Is there a way to see if it tries to write to associations table at all?

4

2 回答 2

2

Try

$this->Tag->saveAll($this->data);

Edit:

Well, you definitely need saveAll(). Additionally, the array of the connected HABTM model needs to be in a certain, slightly curious format. If I remember correctly, it should look like this:

array(
   'Tag' => array('title' => ...),         // primary model
   'Mot' => array(                         // connected HABTM model
      'Mot' => array($id, $id, $id, ...)
   )
);
于 2009-07-23T07:20:32.943 回答
0

自己找到了解决方案。

因为 Mot 可以有很多标签,而标签可以有很多 Mot,并且添加标签是由标签控制器而不是 mots 控制器来处理的,所以标签模型也必须包含 $hasAndBelongsToMany。与 mot 模型相同,只是将 Tag(s) 替换为 Mot(s):

这也应该在标签模型中,而不仅仅是在 mot 模型中:

var $hasAndBelongsToMany = array(
    'Mot' =>
    array(
        'className'              => 'Mot',
        'joinTable'              => 'mots_tags',
        'foreignKey'             => 'tag_id',
        'associationForeignKey'  => 'mot_id',
        'unique'                 => false
    )
);
于 2009-07-23T08:09:35.153 回答