php - 如何在删除孩子之前将父母与孩子分离?(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
,CONSTRAINTuser_user_user_id_foreign
FOREIGN KEY (user_id
) REFERENCESusers
( ))(SQL:从where = xxxid
删除)users
id
解决方案
创建新迁移以更改外键约束
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'
);
}
但在我看来,如果你不使用软删除,这种逻辑最好留给数据库。
推荐阅读
- linux - openstack 将卷附加到实例有问题,但在 linux 上使用 lsblk 命令显示,但无法挂载,也无法使用任何命令删除
- algorithm - 运送人群的最少汽车数量
- google-drive-api - 在 Google Drive 和 Google Cloud Shell Editor 之间链接和同步文件夹
- axios - 在发送请求之前检查 api 端点是否退出 - axios
- javascript - 替换文本但如果包含特定字符则不替换?
- flutter - 如何使用 TDLib Telegram 库保持会话/保存用户身份验证以进行颤动?
- javascript - 在 Typescript/Javascript 中使用 .filter 方法时如何对临时变量进行类型检查
- powerbi - 分割在 pbix 的表/矩阵可视化中不起作用?
- php - 设置函数中的 if 语句
- agile - 如何在用户故事映射会话中将活动映射到任务