设置hasOne与子模型的新实例的关系 [英] Set hasOne relation to new instance of child model

查看:74
本文介绍了设置hasOne与子模型的新实例的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Laravel 4.2,如何在不接触数据库的情况下将模型上的hasOne关系设置为新模型的实例?

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?

我想执行以下操作,但是Laravel将实例视为属性,而不是子关系.

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

推荐答案

为解决我的问题,我创建了一个Trait类,该类已添加到模型中,从而可以设置关系.这样做不会自动设置我的父/子关系值,因此在保存/推送之前,我必须小心手动进行此操作.

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

这篇关于设置hasOne与子模型的新实例的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆