Skip to content

Instantly share code, notes, and snippets.

@shahonseven
Created March 12, 2018 07:41
Show Gist options
  • Save shahonseven/866516b537791084d72593808e93d566 to your computer and use it in GitHub Desktop.
Save shahonseven/866516b537791084d72593808e93d566 to your computer and use it in GitHub Desktop.
Saving associated data in CakePHP 3
CREATE TABLE `address_headers` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`company_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
CREATE TABLE `addresses` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`address_header_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`company_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
<?php
namespace App\Controller;
class AddressHeadersController extends AppController
{
public function initialize()
{
parent::initialize();
$this->Auth->allow('index');
}
public function index()
{
$data = [
'user_id' => 1,
'company_id' => 4,
'addresses' => [
0 => [
'user_id' => 1,
'company_id' => 4,
'name' => 'Aneh'
]
]
];
$entity = $this->AddressHeaders->newEntity();
$entity = $this->AddressHeaders->patchEntity($entity, $data, [
'associated' =>['Addresses']
]);
debug($this->AddressHeaders->save($entity));
}
}
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class AddressHeadersTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->hasMany('Addresses', [
'foreignKey' => 'address_header_id'
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment