【问题标题】:CakePhp 3 Save data in belongsToCakePhp 3 在 belongsTo 中保存数据
【发布时间】:2016-03-22 01:30:28
【问题描述】:

所以,我在将数据保存到数据库时遇到问题

模型表是 ...

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

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

【问题讨论】:

    标签: cakephp cakephp-3.0


    【解决方案1】:

    您正在为输入使用 CakePHP

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

    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'
    ]);
    

    另见

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 2016-04-18
      • 1970-01-01
      • 2019-06-23
      • 2016-04-10
      • 1970-01-01
      相关资源
      最近更新 更多