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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么