2011-02-16 192 views
1

我有一個用戶模型。CakePHP保存模型和關聯模型

它含有看起來像這樣的形式註冊查看:

echo $this->Form->create('User',array(NULL,NULL,'class' => 'signinform')); 
echo $this->Form->input('first_name'); 
... 
echo $this->Form->end('Create Account'); 

當您提交的形式,這樣可以節省這樣的:

$this->User->save($this->data) 

這工作。


我添加了一個表,我的數據庫與外地user_id稱爲addresses這是一個外鍵users.id

我把我的用戶模型:

var $hasMany = 'Address'; 

我添加字段,這樣到註冊表格:

echo $this->Form->input('Address.city'); 

我預計這會在地址表中創建一個新條目並將其與新用戶相關聯。它不會,它會創建一個新用戶,但不在地址表中放置任何內容。

我試圖改變從save保存功能saveAll

$this->User->saveAll($this->data) 

現在沒有得到保存。

我在做什麼錯?

回答

4

CakePHP的保存需要更多的工作來保存這樣的關係。這裏是an example from the documentation

<?php 
function add() { 
    if (!empty($this->data)) { 
     // We can save the User data: 
     // it should be in $this->data['User'] 

     $user = $this->User->save($this->data); 

     // If the user was saved, Now we add this information to the data 
     // and save the Profile. 

     if (!empty($user)) { 
      // The ID of the newly created user has been set 
      // as $this->User->id. 
      $this->data['Profile']['user_id'] = $this->User->id; 

      // Because our User hasOne Profile, we can access 
      // the Profile model through the User model: 
      $this->User->Profile->save($this->data); 
     } 
    } 
} 
?> 

當你進行多個數據庫的變化,你應該考慮using transactions讓他們成功或失敗在一起。如果您不想使用事務,請考慮在請求中途中斷時向用戶顯示的內容。還要考慮數據庫將保留在什麼狀態,以及如何恢復。

+0

這工作,但迴避了一個問題:如果在保存用戶成功,但保存地址/ profile文件失敗 - 怎麼辦?將他們帶回表單將嘗試再次創建新用戶。 –

+0

如果發生這種情況,@John,我會將它們重定向到一個屏幕,以編輯他們剛剛創建的用戶,並將錯誤顯示爲一條flash消息。或者,您可以使用一個事務,以便兩個插入成功或失敗在一起:http://book.cakephp.org/view/1633/Transactions –

+0

感謝您的信息! –

1

您可能還需要把這個地址模型:

var $belongsTo = 'User';