2015-11-19 107 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。