1
votes

I am unable to save data by using cakephp 3 association

AddressHeadersTable

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

AddressesTable

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

Controller Code

$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());
        }

We need to save multiple address under one address header id. when i run above code it create entery in address_header but did not make any entry in addresses table.

1

1 Answers

2
votes

Your data structure should be like this:

$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

When saving hasMany associations, the ORM expects an array of entities named with the plural, underscored version of the association name