laravel 更新与模型的一对一关系

laravel updating one to one relationship with model

我有 1 对 1 模型 (model1 <-1---1->model1.0),我有 model2.0,如下所示:

+------+         +---------+
|      |    +--1-+model1.0 |
|model1+-1--+    +---------+
|      |                    +----------+
+------+                    |model2.0  |
                            +----------+

父模型:

model1 class: { $this->HasOne(ChildModel::class); }

童模:

model1.0 class: {$this->belongsTo(Model1::class); }

问题:如何从 model1.0 转换到 model 2.0?如下所示:

+------+         +---------+
|      |         |model1.0 |
|model1+-1--+    +---------+
|      |    |               +----------+
+------+-   +-------------1-|model2.0  |
                            +----------+

注:

检查 this 部分文档:

Belongs To Relationships

When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model:

$account = App\Account::find(10);

$user->account()->associate($account);

$user->save();

When removing a belongsTo relationship, you may use the dissociate method. This method will set the relationship's foreign key to null:

$user->account()->dissociate();

$user->save();

所以,你可以这样做:

/** Delete the relationship */
// get your model1.0 object
$model1_0 = ChildModel::find($id_1);
// delete the relationship between Model1.0 and Model1
$model1_0->relation()->dissociate();
$model1_0->save();

/** Create the new relationship */
// get your model2.0 object
$model2_0 = ChildModel::find($id_2);
// get your model1 object
$model1 = Model1::find($id);
// relate the models
$model2_0->relation()->associate($model1);
$model2_0->save();

Pd: 我假设 relation() 是子模型中定义的关系的名称。

ChildModel.php

public function relation()
{
    return $this->belongsTo(Model1::class);
}