0

好的,所以我在这个网站和谷歌上做了很多搜索,找到了一些答案,但都没有奏效。我还查看了@ichikaway 的站点和测试程序。连里面的东西都不适合我。此外,当使用“if”语句包装保存/更新时,它总是返回 true,因此我无法进行太多调试。

以下是可能帮助您指导我找到解决方案的相关代码。谢谢!

MyClass 模型定义

class MyClass extends AppModel 
{
var $name = 'MyClass';
var $useTable = 'my_classes';

//var $belongsTo = array();
//var $hasMany = array();

var $useDbConfig = 'mongo';

var $mongoSchema = array(
        '_id' => array('type' => 'integer', 'primary' => true, 'length' => 40),
        'children' => array(
                'child_id' => array('type' => 'integer','length' => 40),
                'child_first_name' => array('type'=>'string'),
                'child_last_name'=>array('type'=>'string'),
                'active'=>array('type' => 'integer', 'length' => 1),
        ),
        'teachers' => array(
                'teacher_id' => array('type' => 'integer','length' => 40),
                'teacher_first_name' => array('type'=>'string'),
                'teacher_last_name'=>array('type'=>'string'),
                'primary'=>array('type' => 'integer', 'length' => 1),
                'active'=>array('type' => 'integer', 'length' => 1),
        ),
        'name' => array('type'=>'string'),
        'active'=>array('type' => 'integer', 'length' => 1),
        'created'=>array('type'=>'datetime'),
        'modified'=>array('type'=>'datetime'),
        );
}

来自我的 StudentsController 的代码

$currentClass = $this->data["MyClass"]["id"];

$classtoedit = $this->MyClass->findById($currentClass);

$addChildToClass = array(
    'MyClass' => array('id'=>$currentClass,
    '$push' => 
        array('children' => 
        array('child_id'=>$newChildId,
            'child_first_name'=>$first_name,
            'child_last_name'=>$last_name,
            'active'=> 1)
        )
      )
    );

print_r($addChildToClass);
$this->MyClass->id = $currentClass;
if($this->MyClass->save($addChildToClass))
{
$this->Session->setFlash("Your child has been successfully added.");

}

编辑: 我能够仅通过 PHP 术语获得所需的功能,但同样,我真的想在 CakePHP 中以正确的方式做到这一点。对于可能追随我的任何其他维护者,我宁愿不要将两者混合在一起。供参考

4

2 回答 2

0

Two thing i want to highlight, please let me know if i am wrong.

1) Why you are setting id twice one in the array variable $addChildToClass and other $this->MyClass->id = $currentClass;

2) What is key ''$push'in the$addChildToClass`?

i think if you will try the array with something like this.. then it will work

$addChildToClass = array(
    array('children' => 
    array('child_id'=>$newChildId,
        'child_first_name'=>$first_name,
        'child_last_name'=>$last_name,
        'active'=> 1)
  )
);

Because any way you are setting the id before updating the field.

于 2013-05-27T18:53:12.787 回答
0

文档看来,您还需要使用mongoNoSetOperator.

在测试中有它的用法示例。

我也认为你需要使用_id而不是id. 在您的用例中,您正在尝试更新现有记录,因此如果驱动程序代码调用insert而不是update您应该得到重复键异常。

于 2013-05-27T09:08:46.233 回答