Art*_*rth 1 php activerecord yii2
我有一个一比一的关系,那里有额外的字段Thing的表ThingExtra。
我正在尝试ThingExtra在创建 new 时初始化一个 new以使用Thing,然后在保存时将它们都Thing保存:
class Thing extends ActiveRecord
{
public function init(){
if($this->isNewRecord){
$this->extra = new ThingExtra();
}
}
public function getExtra(){
return $this->hasOne(ThingExtra::className(),['thing_id' => 'id']);
}
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
$this->extra->thing_id = $this->id;
$this->extra->save();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试创建一个Thing:
$thing = new Thing;
Run Code Online (Sandbox Code Playgroud)
我收到以下异常:
Exception: Setting read-only property: Thing::extra
Run Code Online (Sandbox Code Playgroud)
反正有这个吗?还是我的设计完全有缺陷?
这种方法在 Yii1.1 中对我们非常有效
你不能分配这样的关系,你可以试试这个:
public function init(){
if($this->isNewRecord){
$this->populateRelation('extra', new ThingExtra());
}
}
Run Code Online (Sandbox Code Playgroud)
阅读更多关于 ActiveRecord::populateRelation()