Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 关联只有一个关系而不保存在Laravel 5中_Php_Laravel_Model Associations_Has One - Fatal编程技术网

Php 关联只有一个关系而不保存在Laravel 5中

Php 关联只有一个关系而不保存在Laravel 5中,php,laravel,model-associations,has-one,Php,Laravel,Model Associations,Has One,我创建了一个定制的push()方法,它以级联方式保存所有模型的关系,并收集实体的完整快照和子级详细信息以用于审核日志 一切都与belongsTo配合良好,并且有很多关系。我只是这样做: $ae->target()->associate(new AuditableEntryTarget(["name" => "single target"])); $ae->children->add(new AuditableEntryChild(["name" =

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

一切都与belongsTo配合良好,并且有很多关系。我只是这样做:

    $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关系在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
hasMany
add
用于附加模型而不保存它们,但我找不到hasOne的类似内容


有没有办法将一个新的模型实例附加到hasOne关系中而不立即保存它(比如
associate
for
belongsTo
add
for
hasMany
)?

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

$model->setRelation('child', $childInstance);
不过,令人奇怪的是,Laravel并没有像初始化hasMany一样初始化hasOne关系