2013-04-29 51 views
0

Yii的activerecord-relation-behavior擴展有問題。Yii ActiveRecord-Relation保存不連接模型

我有一個主要的模式:User和子模型:UserPerson(一種型材)

這兩個模型之間的關係是設置好的,模特的行爲正在使用yiiext,但我仍然無法將它們連接起來。

在這種情況下$this是一個模型,它擴展了User模型,並呼籲RegistrationModel

$person = new \UserPerson(); 
$person->full_name = $this->name; 
$person->birthday = $this->birthday; 
$person->gender = $this->gender; 

$this->person = $person; 
$this->person->save(); 

這樣,我應該能夠運行:$this->save() 但我得到這個錯誤:

You can not save a record that has new related records!

我嘗試了很多變化,但只有醜陋的無關聯版本才起作用。 :(

$person->user_id = $this->id; 
//.. 
$person->save(); 

沒有人有一個建議,這個問題

+1

這就是它的工作原理Yii不支持自動保存re相關記錄。你必須手動保存它們。 – 2013-04-29 07:02:14

+0

但這就是爲什麼我使用[activerecord-relation-behavior](https://github.com/yiiext/activerecord-relation-behavior)來獲得這樣的工作,並在模型之間建立真正的關係。 – seniorpreacher 2013-04-29 07:54:32

+0

哦,對不起,錯過了你提到的擴展名。 – 2013-04-29 11:16:48

回答

1

答案是在repository of the extension

"You can not save a record that has new related records!"

You have assigned a record to a relation which has not been saved (it is not in the database yet). Since ActiveRecord Relation Behavior needs its primary key to save it to a relation table, this will not work. You have to call ->save() on all new records before saving the related record.

所以,你必須保存相關的模型,加上相關的元素和然後保存模型

$person = new \UserPerson(); 
$person->full_name = $this->name; 
$person->birthday = $this->birthday; 
$person->gender = $this->gender; 
$person->save(); 
//now $person has a primary key 

$this->person = $person; 
$this->person->save(); 
+0

在這種情況下,'$ person'必須是有效且可保存的。 當我嘗試在沒有用戶標識的情況下保存'$ person'時,出現'外鍵約束失敗'。 ('$ this') 因此無論如何,我必須將用戶標識賦予'$ person'?不是這是** activerecord-relation-behavior **應該關心什麼? – seniorpreacher 2013-04-29 17:44:32

+0

保存模型時,sql數據庫不會給出id,但是id字段需要使用自動增量屬性! – darkheir 2013-04-29 18:39:27

+0

對不起,也許我無法解釋我自己。我有一個User和一個UserPerson類,UserPerson屬於一個User,並帶有一個外鍵。 ('UserPerson.user_id') Btw .:我爲每個'id'字段使用PHP生成的GUID,而不是自動遞增的值。 – seniorpreacher 2013-04-29 20:34:22