2015-11-19 106 views
1

我创建了一个自定义push()方法,以级联方式保存所有模型的关系,并为审核日志收集实体和子级详细信息的完整快照。将HasOne关系关联而不将其保存在Laravel 5中

一切正常与belongsTo和hasMany关系。我只是这样做:

$ae->target()->associate(new AuditableEntryTarget(["name" => "single target"])); 

    $ae->children->add(new AuditableEntryChild(["name" => "one of children"])); 
    $ae->children->add(new AuditableEntryChild(["name" => "two of children"])); 

    // add grandchildren to the first child 
    $ae->children[0]->children->add(new AuditableEntrySubChild(["name" => "one of subchildren for first child"])); 

    // add target subchild 
    $ae->target->subtarget()->associate(new AuditableEntryTargetChild(["name" => "single target child"]));  

    // my custom method which saves and collects to audit log all the children, no matter if they are attached through hasMany or belongsTo 
    $ae->push(); 

但问题是与hasOne的关系。它不提供任何方式将相关模型附加到我的根模型,而不先保存它。 HasOne关系只save()方法在Laravel:

/** 
* Attach a model instance to the parent model. 
* 
* @param \Illuminate\Database\Eloquent\Model $model 
* @return \Illuminate\Database\Eloquent\Model 
*/ 
public function save(Model $model) 
{ 
    $model->setAttribute($this->getPlainForeignKey(), $this->getParentKey()); 

    return $model->save() ? $model : false; 
} 

,正如你看到的,不仅是同事,又节省了模型。为了能够检测字段的所有更改,我的方法要求将关系附加到模型但尚未保存,否则我将无法拦截保存过程并将数据附加到快照。 BelongsToassociatehasManyadd用于附加模型而不保存它们,但是我找不到与hasOne类似的东西。

有没有什么办法可以附加新的模型实例hasOne关系,而不会导致它被保存立即(类似associatebelongsToaddhasMany)?

回答

1

随着Laracasts家伙的帮助下,解决方法似乎是

$model->setRelation('child', $childInstance); 

不过,这是奇怪的是,Laravel不初始化hasOne关系相同的方式,因为它inits的hasMany。