CakePHP 3.1不会保存简单的hasMany关系

时间:2015-09-25 19:05:58

标签: php cakephp cakephp-3.0

我有两个实体,SiteSitesMetaData,我想与hasMany和belongsTo关联。

我按照CakePHP 3.0书创建了所有内容,但出于某种原因,它没有生成或保存关联。

这是我的关系

SitesTable:

$this->hasMany('SitesMetaData', [
    'foreignKey' => 'site_id',
    'dependent' => true
]);

和SitesMetaDataTable(通过烘焙模型自动生成):

$this->belongsTo('Sites', [
    'foreignKey' => 'site_id',
    'joinType' => 'INNER'
]);

这是我的控制器功能:

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

这是$ this-> request->数据的转储和patchEntity之后的$ site:

 /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'

}

另外值得注意。我尝试使用带有TableRegistry::get('SitesMetaData')->newEntity的{​​{1}}创建SitesMetaData并且它有效,所以我将其设置为$this->request->data['sites_meta_data']并将其设置为脏并尝试保存,我收到此错误:

$site->sites_meta_data[]

在这种情况下,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 将是创建网站后的ID。

更新:

尽管在使用newEntity()和belongsToMany关联(据我所知)时,文档仅提及需要执行此操作,但我将22添加到了Site实体的sites_meta_data属性中现在,即使使用$_accessible,我也会收到上述SQL错误,现在它正确构建了SitesMetaData实体。

1 个答案:

答案 0 :(得分:0)

就SQL错误而言:

key不是有效的列名,因为它是sql语言构造。

日期字段看起来像'2015-09-25 18:55:''test'一样,您确定正确填写了吗?并且该错误可能是由于它不是datetime列的有效值。

我建议仅使用/Cake/i18n/Time

用chronos实体填充它们