首页 > 解决方案 > 如何在删除孩子之前将父母与孩子分离?(Laravel 雄辩)

问题描述

我在用户中有父子关系。

我想删除一个孩子。但在此之前,我需要删除父母对孩子的所有引用。

我期待这能奏效 - 但不是:

$child->superiorUsers()->detach($child->id);

$child->delete();

SuperiorUsers() 看起来像这样:

public function superiorUsers()
{
    return $this->belongsToMany(
        'App\Models\User',
        'user_user',
        'user_id',
        'superior_id'
    );
}

知道我做错了什么吗?

编辑: 我正在编写 unitTests 来删除用户,并且我收到关系仍然存在的错误。

SQLSTATE [23000]:完整性约束违规:1451 无法删除或更新父行:外键约束失败(user_user,CONSTRAINT user_user_user_id_foreignFOREIGN KEY ( user_id) REFERENCES users ( ))(SQL:从where = xxxid删除)usersid

标签: phplaraveleloquenteloquent-relationship

解决方案


创建新迁移以更改外键约束

Schema::table('user_user', function (Blueprint $table) {
    $table->dropForeign(['user_id']);
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

这意味着如果一个用户被删除,那么 user_user 上具有已删除 user_id 的任何记录也将被删除。

另一种选择是onDelete('set null')使该字段仅更改为空。


另一种选择是使用用户的deleting事件。

# User model

protected static function booted()
{
    static::deleting(function ($user) {
        $user->superiorUsers()->sync([]);
        $user->inferiorUsers()->sync([]);
    });
}

public function superiorUsers()
{
    return $this->belongsToMany(
        'App\Models\User',
        'user_user',
        'user_id',
        'superior_id'
    );
}

public function inferiorUsers()
{
    return $this->belongsToMany(
        'App\Models\User',
        'user_user',
        'superior_id',
        'user_id'
    );
}

但在我看来,如果你不使用软删除,这种逻辑最好留给数据库。


推荐阅读