如何使用cakephp和mongodb更新记录数组

时间:2013-05-08 10:39:39

标签: php mongodb cakephp

我有问题。我在mongodb中有这种db结构:

id:"xxx",
is_validated: "xxx",
validation_code:"xxx",
profile:[
{
        profile_pic:"xxx",
    firstname:"xxx",
    lastname:"xxx",
}
]

我正在使用cakephp。当我更新记录时,我使用它:

$this->User->set('id', "xxx");
$this->User->set('profile', array('firstname' => 'Benedict'));
$this->User->save()

当我保存记录时,整个配置文件数组都会被删除,只保存“firstname”:

id:"xxx",
is_validated: "xxx",
validation_code:"xxx",
profile:[
{
    firstname:"xxx"
}
]

我需要能够使用cakephp保存名字而不删除mongodb的其他数组记录

2 个答案:

答案 0 :(得分:1)

使用MongoDB时是否遵循标准惯例? (documentation):

// where '1' is the id of your user    
$this->User->read(null, 1);
// set the new value for the field
$this->User->set('profile', array('firstname' => 'Benedict'));
// commit the changes to the database
$this->User->save();

更新

如果上述方法无效,请尝试阅读整个记录并进行相应修改:

// set the active record
$this->User->id = 1;
// read the entire record
$user = $this->User->read();
// modify the field
$user['User']['profile']['firstname'] = 'Benedict';
// save the record
$this->User->save($user);

答案 1 :(得分:0)

发生这种情况的原因是因为您要求使用您传递的数组更新配置文件字段。然后,这将适当地替换当前的配置文件阵列。

为了解决这个问题,你必须传递完整的数组,即你要保留的键及其值以及你想要改变的键。