0
我有這個表:用戶|客戶| (一對一關係)Cakephp 3,表關聯錯誤(一對一關係)
我需要先創建一個用戶,並在創建客戶端後,使用「用戶最後插入的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'
]);
}
}
難道我做錯了什麼?