Cakephp3能够保存数据但无法保存关联

时间:2018-01-31 21:04:17

标签: php cakephp cakephp-3.0

您好,我试图通过Cakephp3框架保存数据。我有两个表Measures和MeasuresUsers。 Measures有很多MeasuresUsers

$data = [
 'name' => $this->request->data['name'],
 'description' => $this->request->data['description'],
 'deleted' => $this->request->data['deleted'],
 'chart_type' => $this->request->data['chart_type'],
 'public' => $this->request->data['public'],
 'user_id' => $this->request->data['user_id']
];
$measure = $this->Measures->newEntity($data,['associated' => ['MeasuresUsers']]);

$measure['measures_users'] = [
                    'user_id' => $user['id'],
                    'chart_type' => $this->request->data['chart_type'],
                    'deleted' => $this->request->data['deleted'],
                    'public' => $this->request->data['public']
];
$this->Measures->save($measure)

我能够将数据保存到Measures表中,但不能保存到关联表(MeasuresUsers)中。我不确定我在这里失踪了什么,感谢任何帮助或评论!

2 个答案:

答案 0 :(得分:3)

@HarryM。已接近,但您希望在创建实体之前将数据放入$data数组(如果您不提供该数据,则associated标记有点无意义!),因为它&# 39; sa有很多关系,我认为你需要将数据放在一个数组数组中:

$data = [
    'name' => $this->request->data['name'],
    'description' => $this->request->data['description'],
    'deleted' => $this->request->data['deleted'],
    'chart_type' => $this->request->data['chart_type'],
    'public' => $this->request->data['public'],
    'user_id' => $this->request->data['user_id'],
    'measures_users' => [
        [
            'user_id' => $user['id'], // Should this be $this->request->data['user_id'] instead?
            'chart_type' => $this->request->data['chart_type'],
            'deleted' => $this->request->data['deleted'],
            'public' => $this->request->data['public'],
        ],
    ],
];
$measure = $this->Measures->newEntity($data, ['associated' => ['MeasuresUsers']]);

$this->Measures->save($measure);

答案 1 :(得分:-1)

来自CakePHP 2.x,我发现你的同事模型是 MeasuresUsers

中设置相关数据时
$measure['measures_users'] = [
    'user_id' => $user['id'],
    'chart_type' => $this->request->data['chart_type'],
    'deleted' => $this->request->data['deleted'],
    'public' => $this->request->data['public']
];

尝试将$ measure ['measures_users']更改为$ measure ['MeasuresUsers']:

$measure['MeasuresUsers'] = [
    'user_id' => $user['id'],
    'chart_type' => $this->request->data['chart_type'],
    'deleted' => $this->request->data['deleted'],
    'public' => $this->request->data['public']
];

CakePHP的模型约定通常假设您拥有数据库中的内容,例如除非在模型本身中另有声明,否则它将movie_tickets和Cake期望的数据库表格作为MovieTicket。