问题
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