Cakephp 2.1手动保存关联对象

时间:2012-04-11 07:49:56

标签: cakephp cakephp-2.1 cakephp-appmodel

Mycakephp版本是2.1.1。

我正在尝试使用saveAll()函数手动保存关联的模型

模型

  • 员工HasOne地址
  • 员工属于部门

所以表

  

雇员(名字,姓氏,年龄,性别,部门标识)

     

地址(first_line,second_line,城市,州,EMPLOYEE_ID)

现在员工创建add.ctp有一个表单,用于接收员工和地址的输入

我知道

  

$这 - >员工 - >白水($这 - >请求 - >数据);

这将保存模型但是 我想手动保存关联

我正在浏览官方的cakephp文件here,我尝试过这样的事情

        $this->Employee->saveAll($data, array(
            'fieldList' => array(
            'Employee' => array('first_name','last_name','age','sex','department_id'),
            'Department' => array('first_line', 'second_line','city','state','employee_id')
            )
        ));

它不起作用,并抛出以下错误

  

注意(8):未定义的变量:数据   [APP \ Controller \ EmployeesController.php,第118行]

     

警告(2):array_keys()期望参数1为数组,给定为null   [CORE \ Cake \ Model \ Model.php,1996行]

我是cakephp初学者。请帮我。

  

$ this-> request-> data:Array

[Employee] => Array
    (
        [first_name] => Jack
        [last_name] => Robert
        [age] => 32
        [sex] => 0
        [Department] => Development
    )

[Address] => Array
    (
        [first_line] => HSR Layout
        [second_line] => 1st Cross
        [city] => Najem
        [state] => Barel
    )

[Department] => Array
    (
        [id] => 3
    )

2 个答案:

答案 0 :(得分:0)

尝试仅使用fieldList参数中的数组:

$this->Employee->saveAll($this->request->data, array('fieldList' => array('Employee.first_name', 'Employee.last_name', 'Employee.age', 'Employee.sex', 'Department.first_line', 'Department.second_line', 'Department.city', 'Department.state', 'Department.employee_id')));

根据手册,fieldList期望“您想要保存的字段数组”。我认为不接受多维数组。

$this->request->data是表单的所有字段,您可以查看debug($this->request->data)

答案 1 :(得分:0)

经过一些研究后我发现了它。

       $data = array(
         'Employee' => array(
         'first_name' => $this->request->data['Employee']['first_name'],
         'last_name'=>$this->request->data['Employee']['last_name'],
         'age'=>$this->request->data['Employee']['age'],
         'sex'=>$this->request->data['Employee']['sex'],
         'department_id'=>$this->request->data['Department']['id']
        ),
         'Adress' => array(
         'first_line' => $this->request->data['Adress']['first_line'],
         'second_line'=>$this->request->data['Adress']['second_line'],
         'city'=>$this->request->data['Adress']['city'],
         'state'=>$this->request->data['Adress']['state']
        )

    );


            $this->Employee->saveAll($data, array('deep' => true))

这样做。