【问题标题】:Laravel hasMany relationship detach allLaravel hasMany 关系分离所有
【发布时间】:2019-10-02 23:01:55
【问题描述】:

是否有一种简单的解决方案可以通过模型上的 hasMany Relation 分离(而不删除)所有相关模型?

例如,我有两个表:

  • 学院(身份证、姓名)

  • 学生(id、name、college_id(nullable))

在学院模型中,我定义了这种关系:

class College extends Model
{
    public function students()
    {
        return $this->hasMany('App\Student','college_id','id');
    }
}

将所有在校大学生从学院中分离出来的最佳方法是什么(即,获取学院的所有学生并将他们的college_id 设置为null)?

有没有一种简单的方法可以使用 eloquent 将所有学生从 College 模型中分离出来?

类似

class College extends Model
{
    ...
    public function detachAllStudents()
    {
        ...
    }
}

附:已经读过这个问题Laravel hasMany detach,但是当我尝试将它应用到我的应用程序时出现错误

【问题讨论】:

  • 分离多对多我认为你需要使用 dissociate()
  • 不,dissociate() 仅适用于 hasOne 关系。

标签: laravel orm eloquent


【解决方案1】:

尽管 Imran 的回答非常适合这种情况,但我会添加一种更通用的方法。假设$college 尊重接口而不是实现,您在运行时不会知道外键。

<?php

use Illuminate\Database\Eloquent\Relations\HasMany;

interface HasStudents {
    public function students(): HasMany;
}

class College extends Model implements HasStudents
{
    public function students(): HasMany;
    {
        return $this->hasMany(Student::class, 'college_id', 'id');
    }
}

function detachStudents(HasStudents $model): void {
    $studentsRelationship = $model->students();
    $studentsRelationship->update([
        $studentsRelationship->getQualifiedForeignKeyName() => null
    ]);
}

detachStudents($college);

【讨论】:

    【解决方案2】:

    是的,您可以按如下方式分离所有大学生。实际上,我们已经在您的students 表中拥有了college_id,我们必须以某种方式使这个college_id 为空。这在 Eloquent 中不称为分离。当您拥有many to many 关系时,就会出现detach 这个词。所以,让我们更新学生,看看它是否有效。

    $college->students()->update(['college_id' => null);
    

    所以,你的方法可以如下完成:

    public function detachAllStudents()
    {
        $college->students()->update(['college_id' => null]);
    }
    

    就是这样!

    【讨论】:

    • 感谢您的回答,但调用 $this->students()->detach();在模型类中导致“调用未定义的方法 Illuminate\Database\Eloquent\Relations\HasMany::detach()”
    • 对不起,你这么告诉分离,我认为这是多对多的关系。实际上你有一对多的关系。在这种情况下,我们必须改用update() 方法。我已经更新了答案。请检查它是否有效。
    • 是的,这是正确的答案,终于得到了聪明的一线解决方案,谢谢!)
    【解决方案3】:

    直接来自文档https://laravel.com/docs/5.8/eloquent-relationships

    切换关联

    多对多关系还提供了一种切换方法,可以“切换”给定 ID 的附件状态。如果当前附加了给定的 ID,它将被分离。同样,如果它当前是分离的,它将被附加:

    $user->roles()->toggle([1, 2, 3]);
    

    【讨论】:

    • 感谢您的回答,但调用 $this->students()->toggle([1]);;在模型类中导致“调用未定义的方法 Illuminate\Database\Eloquent\Relations\HasMany::toggle()
    • 我以为你有一个多对多的关系,因为你使用了分离这个词。看到 Imran 成功地回答了您的问题,抓住了术语上的差异。
    猜你喜欢
    • 2022-11-23
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2020-03-25
    • 2021-03-22
    • 2021-09-24
    相关资源
    最近更新 更多