2012-01-12 18 views
1

我開始使用Datamapper並出現一些錯誤。我想如果我創建一個對象,一個相關的對象,然後我保存了這個關係,那麼這兩個對象都是保存的。在Codeigniter中保存數據映射關係

$u = new User(); 
$u->where('id', $id)->get(); 

$p = new User_profile(); 
$p->name = 'xx'; 

$u->save($p); 

其實如果我這樣做,配置文件不會被保存。當然不是關係。如果我這樣做:

$u = new User(); 
$u->where('id', $id)->get(); 

$p = new User_profile(); 
$p->save(); 
$p->name = 'xx'; 

$u->save($p); 

都保存但配置文件完全是空的。沒有參數被保存,但id和Datamapper默認(創建和更新)

此行爲是否正確,或者我錯過了什麼?

謝謝!

+0

聽起來對我來說,如果你可能沒有正確設置模型。你可以發佈它們嗎? – 2012-01-12 19:12:59

+0

不,模型應該沒問題,因爲它在某些情況下有效。我認爲這將與答案有關。謝謝! – luso 2012-01-13 16:05:45

回答

1

在文檔:http://datamapper.wanwizard.eu/pages/save.html保存新對象及其在一個單一的通話保存現有對象和它在一個單一的通話部分關係的關係,它說明了如何處理DataMapper的這個。

這是怎麼回事save永遠不會被調用User_profile()。您需要一個尚未持久化對象上進行調用save(),所以這應該爲你工作:

$u = new User(); 
$u->where('id', $id)->get(); 

$p = new User_profile(); 
$p->name = 'xx'; 

$p->save($u); 
+0

所以我誤解了文檔。謝謝你的回答,我會解決並回復。謝謝! – luso 2012-01-13 16:06:39

1
$u = new User(); 
$u->where('id', $id)->get(); 

//passing the user object $u to the user_profile object ensures that 
//data-mapper fills $p with any related information in the database if that exists 
//or just the id attribute for the relationship. 
//This way, $p will not be empty even though its fields might not b complete, 
//but the relating attribute which should be 'user_id' will have a valid value 
//in the 'profiles' table 
$p = new User_profile($u); 

$p->name = 'xx'; 

$u->save(); 
$p->save(); 

在這個月底,對象$ P現在將在下面的值最低

echo $p->user_id //prints out $id; 
echo $p->name  //prints out xx. 

調用保存方法後,必須絕對可以保存爲,如果,如果這樣的行已經存在數據不前或更新存在的輪廓表中的新條目。

希望這可以解決您的問題。

+0

非常感謝。我還沒有嘗試,但似乎是非常正確的。 – luso 2012-01-13 16:08:02