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

时间:2015-04-06 22:05:29

标签: cakephp cakephp-3.0

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

我需要先创建一个用户,然后在创建客户端后,使用"用户最后插入的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']);
}

-

ClientsTable

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

我做错了吗?

1 个答案:

答案 0 :(得分:1)

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

如果是hasOne关联,则数据需要类似

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

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