CakePHP HABTM 问题
可能是一个新手问题,因为我想在空闲时间看看所有这些“PHP 框架”是什么。
首先,我想为多张照片添加多个标签。 我有一个标签模型和 mot 模型(照片)。 mot 模型的片段:
var $hasAndBelongsToMany = array(
'Tag' =>
array(
'className' => 'Tag',
'joinTable' => 'mots_tags',
'foreignKey' => 'mot_id',
'associationForeignKey' => 'tag_id',
'unique' => false
)
);
在 add() 的标签控制器中,我有:
$this->Tag->save($this->data);
当 print_r'ing $this->data 时,我看到
Array
:( [莫特] => 大批 ( [id] => 2 )
[Tag] => Array
(
[title] => 21e21e
)
)
标签被插入到标签表中,但没有任何内容被插入到mottags(mot和标签之间有下划线,但当我在这里写它而不是成为下划线时它是斜体)表。 我的 mots_tags 数据库模式:(sqlite)
create table mots_tags (id INTEGER PRIMARY KEY, mot_id INTEGER, tag_id INTEGER)
有什么线索说明为什么 Cake 只写入 Tags 表而不写入关联表吗? 我没有收到任何 SQL 错误。 有没有办法查看它是否尝试写入关联表?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
编辑:
嗯,你肯定需要
saveAll()
。 此外,连接的 HABTM 模型的数组需要采用某种有点奇怪的格式。 如果我没记错的话,它应该是这样的:Try
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:我自己找到了解决方案。
因为 Mot 可以有很多标签,而 Tags 可以有很多 Mot,并且标签添加是由标签控制器而不是 mots 控制器处理的,所以标签模型还必须包含 $hasAndBelongsToMany。 与 mot 模型相同,只是将标签替换为 Mot:
这也应该在标签模型中,而不仅仅是在 mot 模型中:
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: