2013-04-29 71 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