I have two objects, Site and SitesMetaData , which I want to associate with hasMany and belong to the association.
I created everything according to the CakePHP 3.0 book, but for some reason did not generate or save the association.
Here are my relationships
SitesTable:
$this->hasMany('SitesMetaData', [ 'foreignKey' => 'site_id', 'dependent' => true ]);
and SitesMetaDataTable (automatically generated when baking a model):
$this->belongsTo('Sites', [ 'foreignKey' => 'site_id', 'joinType' => 'INNER' ]);
Here is my controller function:
$site = $this->Sites->newEntity(); if ($this->request->is('post')) { $site = $this->Sites->patchEntity($site, $this->request->data, ['associated' => ['SitesMetaData']]); if ($this->Sites->save($site)) { $this->Flash->success(__('The site has been saved.')); return $this->redirect(['_name' => 'admin:home']); } else { $this->Flash->error(__('The site could not be saved. Please, try again.')); } }
Here is a dump of $ this-> request-> data and $ site after patchEntity:
/src/Controller/Admin/SitesController.php (line 33) [ 'title' => 'test', 'alias' => 'sdfs', 'layout' => 'default', 'sort' => '3', 'sites_meta_data' => [ (int) 0 => [ 'key' => 'keyword', 'value' => 'test' ] ] ] /src/Controller/Admin/SitesController.php (line 34) object(App\Model\Entity\Site) { 'title' => 'test', 'alias' => 'sdfs', 'layout' => 'default', 'sort' => (int) 3, '[new]' => true, '[accessible]' => [ 'title' => true, 'alias' => true, 'layout' => true, 'sort' => true ], '[dirty]' => [ 'title' => true, 'alias' => true, 'layout' => true, 'sort' => true ], '[original]' => [], '[virtual]' => [], '[errors]' => [], '[repository]' => 'Sites' }
Also pay attention. I tried creating SiteMetaData using TableRegistry::get('SitesMetaData')->newEntity with $this->request->data['sites_meta_data'] and it worked, so I set it to $site->sites_meta_data[] and installed it as dirty and tried to save and I get this error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key, value, created, modified) VALUES (22, 'keyword', 'test', '2015-09-25 18:55:' at line 1
In this case, 22 will be the identifier of the site after its creation.
UPDATE:
Despite the fact that the documents only mention the need to use newEntity () and associations belonging toMany (as far as I can see), I added sites_meta_data to the entity attribute $_accessible and now I get the above SQL error even when using $this->Sites->patchEntity($site, $this->request->data ...) , and now it correctly creates the SitesMetaData object.