I have two entities, Site
and SitesMetaData
that I want to relate with a hasMany and belongsTo association.
I created everything as per the CakePHP 3.0 book but for some reason it's not generating or saving the association.
Here are my relationships
SitesTable:
$this->hasMany('SitesMetaData', [
'foreignKey' => 'site_id',
'dependent' => true
]);
and SitesMetaDataTable (auto generated by baking the 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 of note. I tried creating the SitesMetaData 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 set it as dirty and tried saving 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
would be the ID of the site after it gets created.
UPDATE:
Despite the docs only mentioning needing to do it when using newEntity() and belongsToMany associations (as far as I can see), I added sites_meta_data
to the Site entity's $_accessible
attribute and now I get the above SQL error even while using $this->Sites->patchEntity($site, $this->request->data ...)
and it now properly builds the SitesMetaData entity.