CakePHP 3 新字段无法正确保存

CakePHP 3 new fields won't save correctly

我有一个带有电子邮件和密码的用户模型。我将字段 first_name 和 last_name 添加到我的数据库中,添加视图的表单如下所示:

     9  <div class="users form large-12 medium-9 columns">
     10     <?= $this->Form->create($user) ?>
     11     <fieldset>
     12         <legend><?= __('New Account') ?></legend>
     13         <?php
     14             echo $this->Form->input('email');
     15             echo $this->Form->input('first_name');
     16             echo $this->Form->input('last_name');
     17             echo $this->Form->input('password');
     18
     19         ?>
     20     </fieldset>
     21     <?= $this->Form->button(__('Submit')) ?>
     22     <?= $this->Form->end() ?>
     23 </div>                            

电子邮件和密码保存没有问题,但 first_name 和 last_name 永远不会。这是控制器功能。添加注释行会导致 first_name 字段保存,但很明显我不应该这样做。

     46     public function add()
 47     {
 48         $user = $this->Users->newEntity();
 49         if ($this->request->is('post')) {
 50             $user = $this->Users->patchEntity($user, $this->request->data);
 51             //$user->first_name = $this->request->data['first_name'];
 52             if ($this->Users->save($user)) {
 53                 $this->Flash->success(__('The user has been saved.'));
 54                 return $this->redirect(['action' => 'index']);
 55             } else {
 56                 $this->Flash->error(__('The user could not be saved. Please, try again.'));
 57             }
 58         }
 59         $books = $this->Users->Books->find('list', ['limit' => 200]);
 60         $this->set(compact('user', 'books'));
 61         $this->set('_serialize', ['user']);
 62     }

有谁知道为什么会这样?我尝试清除模型缓存但没有任何改变。

谢谢!

使用

批量分配新属性
$this->Model->patchEntity($entity, $this->request->data);

您必须将它们列入白名单。在这种情况下,在 /src/Model/Entity/User.php 文件中:

 1     protected $_accessible = [
 2         'email' => true,
 3         'password' => true,
 4         'first_name' => true, //add this
 5         'last_name' => true,  //add this
 6     ];

另一方面,直接分配属性(如 $user->first_name = $this->request->data['first_name'];)总是可行的。

更多信息:http://book.cakephp.org/3.0/en/orm/entities.html#mass-assignment

另一种方法是在创建实体时设置可访问的字段。

$user = $this->Users->newEntity($this->request->data, [
    'accessibleFields' => [
          'email' => true,
          'password' => true,
          'first_name' => true,
          'last_name' => true, //or you could just use '*' => true
    ] 
]);

也不需要调用newEntity再调用patchEntity数据,可以像我的例子一样先把数据给newEntity