laravel使用模型更新一对一关系

时间:2018-10-26 15:35:41

标签: php laravel laravel-5 eloquent laravel-5.7

我有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  |
                            +----------+

注意:

  • model1和model1.0在数据库中,但model2.0仍在控制器中作为对象变量。

  • model1.0和model2.0是同一模型类的对象

1 个答案:

答案 0 :(得分:0)

查看文档的this部分:

  

属于关系

     

在更新surface_array = [[0 for i in range (0,10)] for j in range(0,10)] surface_array[1][1] = 1 surface_array[0][1] = 1 surface_array[2][0] = 1 surface = np.array(surface_array) print(surface) floodfill(0, 0, 0, 100) print(surface) 关系时,您可以使用belongsTo   方法。此方法将在子模型上设置外键:

associate
     

在删除$account = App\Account::find(10); $user->account()->associate($account); $user->save(); 关系时,您可以使用belongsTo   方法。此方法会将关系的外键设置为dissociate

null

因此,您可以执行以下操作:

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

$user->save();

Pd:我假设/** 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(); 是子模型中定义的关系的名称。

ChildModel.php

relation()
相关问题