问题
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?
回答1:
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, ...)
)
);
回答2:
Found a solution myself.
Because Mot's can have many tags, and Tags can have many Mots, and Tags adding is handled by tags controller instead of mots controller, tag model must also contains $hasAndBelongsToMany. Same as in mot model, just with Tag(s) replaced bu Mot(s):
This should have been in tag model also, not only in mot model:
var $hasAndBelongsToMany = array(
'Mot' =>
array(
'className' => 'Mot',
'joinTable' => 'mots_tags',
'foreignKey' => 'tag_id',
'associationForeignKey' => 'mot_id',
'unique' => false
)
);
来源:https://stackoverflow.com/questions/1170141/cakephp-habtm-question