【问题标题】:laravel updating one to one relationship with modellaravel 更新与模型的一对一关系
【发布时间】:2019-03-31 09:51:23
【问题描述】:

我有 1 对 1 模型 (model1 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是同一个模型类的对象

【问题讨论】:

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


    【解决方案1】:

    查看this部分文档:

    属于关系

    更新belongsTo 关系时,您可以使用associate 方法。此方法将在子模型上设置外键:

    $account = App\Account::find(10);
    
    $user->account()->associate($account);
    
    $user->save();
    

    删除belongsTo 关系时,您可以使用dissociate 方法。该方法会将关系的外键设置为null

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

    所以,你可以这样做:

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

    ChildModel.php

    public function relation()
    {
        return $this->belongsTo(Model1::class);
    }
    

    【讨论】:

    • 谢谢,我不想删除model1_0 - 所以当我删除$model1_0->relation()->dissociate(); 时,它会删除数据库中的记录吗?
    • 不,它只会设置为null 存储在Model1.0 对象中的外键。
    • 我做了:model1->model10()->dissociate() 但我收到了:BadMethodCallException with message 'Call to undefined method Illuminate/Database/Eloquent/Relations/HasOne::disassociate()'
    • 哦,你告诉我我应该脱离子模型?
    • dissociate() 需要在子对象中调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    相关资源
    最近更新 更多