Set hasOne relation to new instance of child model

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();

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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');
  }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x