Created
March 12, 2018 07:41
-
-
Save shahonseven/866516b537791084d72593808e93d566 to your computer and use it in GitHub Desktop.
Saving associated data in CakePHP 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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