关联HasOne关系而不在Laravel 5中保存它

时间:2015-11-19 16:20:59

标签: php laravel model-associations has-one

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

使用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关系在Laravel中只有save()方法:

 /**
 * 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;
}

正如您所看到的那样,不仅可以关联,还可以保存模型。为了能够检测字段的所有更改,我的方法要求关系附加到模型但尚未保存,因为否则我将无法拦截保存过程并将数据附加到我的快照。 BelongsTo associate hasManyadd associate附加模型但尚未保存,但我找不到任何与hasOne类似的内容。

有没有办法将新模型实例附加到hasOne关系而不会立即保存(类似belongsTo addhasMany {{1} }})吗

1 个答案:

答案 0 :(得分:2)

在Laracasts人的帮助下,解决方法似乎是

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

但是,奇怪的是,Laravel并没有像hasMany那样初始化hasOne关系。