在 CakePHP 中使用 HABTM 进行保存
我正在一次性创建多个关联,并且在保存方面存在一些问题。
我有以下代码:
<?php
foreach($userData as $user) {
$data = array('User' => array('id' => $user['id']), 'Site' => array('id' => $user['site_id']));
$this->User->save($data);
}
?>
尽管我总是遇到相同的问题,但我已经尝试以不同的方式格式化数据数组。 当插入新条目时,先前的条目会被移动,或者当前条目会被更新。
尽管我需要触发行为,但我可以使用以下内容。
$this->User->SiteUser->save($data);
编辑:另外 $this->User->create(); 似乎没什么作用。
I am creating multiple associations in one go and there are a few problems when it comes to saving.
I have the following code:
<?php
foreach($userData as $user) {
$data = array('User' => array('id' => $user['id']), 'Site' => array('id' => $user['site_id']));
$this->User->save($data);
}
?>
I have experimented with formatting the data array in different ways although I always encounter the same problems. Either the previous entries get moved when a new one is inserted or the current one gets updated.
I could just use the following although I need a behavior to trigger.
$this->User->SiteUser->save($data);
Edit: Also $this->User->create(); doesn't seem to do much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IRC 帮助找出了问题所在,一旦unique键设置为false,一切都能够正确保存。
The IRC helped work out what was wrong, once the unique key was set to false everything was able to save correctly.
尝试在新的
save()
之前重置id
,可能在两种模型上:Cake 决定是否根据设置的
id
更新或插入条目,并且save()
自动设置id
。 不知道为什么create()
不为您处理这个问题。另外,如果您想保存 HABTM 数据,您应该需要使用
saveAll()
而不是save()
。 另请参阅此问题。Try resetting the
id
before a newsave()
, possibly on both models:Cake decides whether to update or insert entries based on the set
id
, andsave()
sets anid
automatically. Not sure whycreate()
doesn't take care of this for you.Also, if you want to save HABTM data, you should need to use
saveAll()
instead ofsave()
. Also see this question.