duandeng7132 2018-10-26 07:35
浏览 180
已采纳

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

I have 1 to 1 model (model1 <-1---1->model1.0) and i have model2.0 like below:

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

Parent model:

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

Child Model:

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

Questions: how do i swing from model1.0 to model 2.0? like below:

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

note:

  • model1 and model1.0 is in database but model2.0 is still in controller as object variable.

  • model1.0 and model2.0 is object of the same model class

  • 写回答

1条回答 默认 最新

  • donglv6960 2018-10-26 07:52
    关注

    Check this part of the documentation:

    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();
    

    So, you can just do this:

    /** 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: I'm assuming that relation() is the name of the relationship defined in the child model.

    ChildModel.php

    public function relation()
    {
        return $this->belongsTo(Model1::class);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?