Cakephp 3-将数据保存到归属关系表

时间:2018-08-10 11:20:27

标签: cakephp model-view-controller cakephp-3.0 has-and-belongs-to-many

Cakephp3中,有以下表格:

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  `created` datetime NOT NULL,
  `modified` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `roles` (
  `id` int(11) NOT NULL,
  `title` varchar(45) DEFAULT NULL,
  `created` datetime NOT NULL,
  `modified` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `roles_users` (
  `id` int(11) NOT NULL,
  `note` text,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  `role_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我的目的是在“用户添​​加和编辑”视图(以及相关的控制器操作)内编辑表“ roles_users”中的可用字段。我认为https://book.cakephp.org/3.0/en/views/helpers/form.html#associated-form-inputs,我的用户视图(编辑)如下:

<div class="users form large-9 medium-8 columns content">
    <?= $this->Form->create($user) ?>
    <fieldset>
        <legend><?= __('Edit User') ?></legend>
        <?php
            echo $this->Form->control('name');

            echo $this->Form->control('roles.0._joinData.role_id', ['type'=>'select', 'options' => $roles]);
            echo $this->Form->control('roles.1._joinData.role_id', ['type'=>'select', 'options' => $roles]);
            echo $this->Form->control('roles.2._joinData.role_id', ['type'=>'select', 'options' => $roles]);

        ?>
    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
</div>

基本的控制器动作是:

public function edit($id = null)
    {

        $user = $this->Users->get($id, [
            'contain' => ['Roles']
        ]);

        if ($this->request->is(['patch', 'post', 'put'])) {

            $user = $this->Users->patchEntity($user,$this->request->getData());
            pr($this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
        $roles = $this->Users->Roles->find('list', ['limit' => 200]);
        $this->set(compact('user', 'roles'));
    }

在访问编辑操作时显示正确的数据。但是,在提交数据(甚至保持不变)时,新记录将保存到表“角色”中。我该如何更新控制器动作和相关视图,以将数据写入表“ roles_users”?

2 个答案:

答案 0 :(得分:0)

您需要像下面那样在patchEntity中添加关联的模型

$user = $this->Users->patchEntity($user,$this->request->getData(), [
    'associated' => ['RolesUsers']
]);

https://book.cakephp.org/3.0/en/orm/saving-data.html#

答案 1 :(得分:0)

echo $this->Form->control('roles.0._joinData.role_id', ['type'=>'select', 'options' => $roles])

收件人:

echo $this->Form->control('roles.0.id', ['type'=>'select', 'options' => $roles])
echo $this->Form->control('roles.1.id', ['type'=>'select', 'options' => $roles])