duandeng7132 2018-10-26 15: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 15: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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?