Set hasOne relation to new instance of child model

跟風遠走 提交于 2019-12-12 03:56:26

问题


Using Laravel 4.2, how can I set a hasOne relation on a model to an instance of a new model without touching the database?

I want to do the following, but Laravel is treating the instance as a property, not a child relation.

class ParentClass extends \Eloquent {
  public function child() {
    return $this-hasOne('ChildClass', 'child_id', 'parent_id');
  }
}

$parent = new ParentClass();
$parent->child = new ChildClass();

回答1:


To get through my problem, I have created a Trait class that I added to my models that allows me to set a relation. Doing this does not automatically set my parent/child relation values so I have to be careful to do this manually before I save/push.

trait ModelSetRelationTrait
{
  public function setRelation($key, $model)
  {
    $this->relations[$key] = $model;
  }
}

class ParentClass extends \Eloquent {
  use ModelSetRelationTrait;
  public function child() {
    return $this-hasOne('ChildClass', 'child_id', 'parent_id');
  }
}


来源:https://stackoverflow.com/questions/43416180/set-hasone-relation-to-new-instance-of-child-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!