2015-04-06 52 views
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' 
    ]); 
    } 
} 

難道我做錯了什麼?

回答

0

你最好遵循約定而不是試圖將自己的解決方案混合在一起。一旦正確關聯,您所需要做的就是根據您的關聯以正確格式化的方式傳遞請求數據,CakePHP將負責處理其餘部分,包括在保存關聯數據之前插入正確的外鍵值。

hasOne協會的情況下,數據將需要看起來像

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

請檢查有關如何保存數據的更多詳細信息,文檔: