1

Mycakephp 版本是 2.1.1。

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

模型

  • 员工有一个地址
  • 员工所属部门

所以表

员工(名字,姓氏,年龄,性别,部门ID)

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

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

我知道

$this->Employee->saveAll($this->request->data);

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

我在这里浏览了官方 cakephp 文档 ,我尝试过这样的事情

        $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: 数组

(

[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
    )

)

4

2 回答 2

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).

于 2012-04-11T09:54:56.823 回答
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))

这会做到的。

于 2012-04-12T09:56:43.063 回答