保存关联数据cakephp 3时出错

时间:2018-03-12 06:17:36

标签: cakephp cakephp-3.0

我无法使用cakephp 3关联保存数据

AddressHeadersTable

$this->hasMany('Addresses', [
            'foreignKey' => 'address_header_id'
        ]);

AddressesTable

$this->belongsTo('AddressHeaders', [
            'foreignKey' => 'address_header_id',
        ]);

控制器代码

$data = [
            'user_id' => 1,
            'company_id' => 4,
            'address' => [
                'user_id' => 1,
                'company_id' => 4,
                'name' => 'Aneh'
            ]
        ];

        $entity = $this->AddressHeaders->newEntity();
        $entity = $this->AddressHeaders->patchEntity($entity, $data, [
            'associated' =>['Addresses']
        ]);
        if($this->AddressHeaders->save($entity)){
            echo "save";
        }else{
            pr($entity->errors());
        }

我们需要在一个地址标头ID下保存多个地址。当我在代码上面运行时,它在address_header中创建了entery,但没有在地址表中创建任何条目。

1 个答案:

答案 0 :(得分:1)

您的数据结构应如下所示:

$data = [
    'user_id' => 1,
    'company_id' => 4,
    'addresses' => [
        [
            'user_id' => 1,
            'company_id' => 4,
            'name' => 'Aneh'
        ]
    ]
];

https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-hasmany-associations

  

当保存hasMany关联时,ORM需要一组实体   以复数,下划线的关联名称

命名