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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?