Cakephp 3.0无法更新关联的模型

时间:2015-10-12 12:08:49

标签: cakephp orm cakephp-3.0

UserMastersTable.php:

$this->hasOne('PersonMasters', [
            'className' => 'PersonMasters',
            'foreign_key' => 'user_master_id',
            'dependent' => true
        ]);

控制器代码:

public function editUser($id) {

        $countryOptions = $this->Countries->find('list')->select(array('id', 'name'));

        $this->set(compact('countryOptions'));

        $user_detail = $this->UserMasters->get($id, ['contain' => ['PersonMasters']]);
        $this->set('user_detail', $user_detail);

      if ($this->request->is('post')) 
        {
        $user=$this->UserMasters->newEntity();

         $user = $this->UserMasters->patchEntity($user,$this->request->data,['associated'=>  ['PersonMasters']]);


            $this->UserMasters->save($user,['associated'=>  ['PersonMasters']]);

        }

    }

它不会更新数据。每次在user_mastersperson_masters表中保存新记录时。那么如何更新user_mastersperson_masters

中的数据

如果我在.ctp视图文件中设置一个包含user_masters id的隐藏字段,那么它只更新user_masters条记录,并在person_masters中添加新记录表

我已在每个实体中分配' * '=true,包括UserMasters。它仍然无法正常工作。 那么如何更新cakephp3中的user_masters和关联表。

1 个答案:

答案 0 :(得分:3)

问题中的问题是创建并修补了新实体,发布的数据不包含主键值,因此它始终是插入。

修复方法是修补$user_detail对象(已包含现有主键值,因为它已从数据库中读出),然后保存:

$user = $this->UserMasters->patchEntity(
    $user_detail, 
    $this->request->data, 
    ['associated' => ['PersonMasters']]
);
$this->UserMasters->save($user,['associated'=>  ['PersonMasters']]);