CakePhp 3在belongsTo中保存数据

时间:2016-03-21 12:28:20

标签: cakephp cakephp-3.0

所以,我将数据保存到DB

有问题

模型表是 ...

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

...

我想在行中存储新地址,数据结构是

object(App\Model\Entity\Address) {

    'type' => (int) 1,
    'Users' => [
        'user_id' => '9'
    ],
    'short_name' => 'Test',
    'long_name' => 'test',
    'additional_name' => 'test',

我试过控制器

if ($this->request->is('post')) {
                $address = $this->Addresses->patchEntity($address, $this->request->data, ['associated' => ['Users.user_id']]);
                if ($this->Addresses->save($address)) {
                    $this->Flash->success(__('The address has been saved.'));
                    return $this->redirect(['action' => 'index']);
                } else {
                    $this->Flash->error(__('The address could not be saved. Please, try again.'));
                }

在我的模板视图中,这是输入字段

echo $this->Form->input('Users.user_id', ['type' => 'select', 'options' => $groups, 'class' => 'form-control']);
echo $this->Form->input('short_name', ['class' => 'form-control']);
echo $this->Form->input('long_name', ['class' => 'form-control']);

那么,我该怎么办?如何重组数据结构? 谢谢!

1 个答案:

答案 0 :(得分:0)

您正在为输入使用CakePHP< = 2.x样式的命名约定,而不再是CakePHP 3.x的工作方式。

请参阅有关如何为关联数据创建输入的文档:

<强> Cookbook > Views > Helpers > Form > Creating Inputs for Associated Data

您必须使用关联的相应属性名称,就像在读取数据时在实体中显示的那样。对于belongsTo关联,默认情况下,这是关联别名的单数,下划线变体,因此在您的情况下user,即

echo $this->Form->input('user.user_id', [
    'type' => 'select',
    'options' => $groups,
    'class' => 'form-control'
]);

另见