Cakephp 3, table 关联错误(一对一关系)

Cakephp 3, table association error (one to one relationship)

我有这个表: |用户 |客户 | (一对一关系)

我需要先创建一个用户,然后创建客户端,然后 "user last inserted id"。以下是我的尝试:

客户端控制器

public function add()
{
    $userId = null;
    $client = $this->Clients->newEntity();
    $client = $this->Clients->patchEntity($client, $this->request->data);

    if ($this->request->is('post')) {
        $user = $this->Clients->User->newEntity();
        $user->role_id = 2; // client
        $user->username = $this->request->data['cnpj'];
        $user->password = $this->request->data['cnpj'];

        if ($this->Client->User->save($user)) {
            $userId = $this->Client->User->getLastInsertId();
        }
    }
    if (isset($userId) && $this->request->is('post')) {
        $client = $this->Clients->patchEntity ( $client, $this->request->data );
        $client->user_id = $userId;
        if ($this->Clients->save ($client)) {
            $this->Flash->success ('The client has been saved.');
            return $this->redirect (['action' => 'index']);
        } else {
            $this->Flash->error ( 'The client could not be saved. Please, try again.' );
        }
    }

    $regions = $this->getRegions();

    $this->set(compact('client', 'regions'));
    $this->set('_serialize', ['client']);
}

--

客户表

class ClientsTable extends Table
{

/**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */
 public function initialize(array $config)
 {
     $this->table('clients');
     $this->displayField('id');
     $this->primaryKey('id');
     $this->addBehavior('Timestamp');
     //$this->belongsTo('Users', [
     $this->hasOne('Users', [
         'foreignKey' => 'users_id'
     ]);
  }
}

我是不是做错了什么?

你最好遵循约定,而不是试图摸索出你自己的解决方案。正确关联后,您需要做的就是根据您的关联以正确格式的方式传递请求数据,CakePHP 将负责其余的工作,包括在保存关联数据之前插入正确的外键值。

hasOne 关联的情况下,数据需要类似于

[
    'username' => '...',
    'password' => '...',
    'client' => [
        'some_client_column' => '...'
    ]
]

请查看有关如何保存数据的文档以获取更多详细信息: