mysql - 删除具有关系的相关列的最佳方法
问题描述
例如,我们有 p_categories 表和 product 表。
p_categories 表是:
╔═══╦════════════╦═════════════╗
║ ║ id ║ name ║
╠═══╬════════════╬═════════════╣
║ 1 ║ 1 ║ tech ║
║ 2 ║ 2 ║ food ║
║ 3 ║ 3 ║ sport ║
╚═══╩════════════╩═════════════╝
产品表是:
╔════╦═══════════════╦═════╗
║ id ║p_categories_id║name ║
╠════╬═══════════════╬═════╣
║ 1 ║ 1 ║phone║
╠════╬═══════════════╬═════╣
║ 2 ║ 2 ║spoon║
╠════╬═══════════════╬═════╣
║ 3 ║ 2 ║fork ║
╚════╩═══════════════╩═════╝
在 pcategory 模型中,我有:
public function products()
{
return $this->hasMany(Product::class, 'p_categories_id');
}
在产品模型中:
public function category()
{
return $this->belongsTo(PCategory::class,'p_categories_id', 'id');
}
当我尝试删除技术类别时,product table
id=1, p_categories_id=1, name=phone
必须同时删除该行。
可能我认为的解决方案:
1)将列类型更改为级联。我读了一些帖子。人们大多不推荐这个。
2)在类别模型中添加新功能
protected static function boot() {
parent::boot();
static::deleting(//something, i don't know how to make.); }
我需要用这种方法改变整个项目。因为一个都没有。我正在寻找最好的方法来做到这一点。我写了 2 个可能的解决方案,但我仍然不知道如何正确地制作它们。我希望我能解释一下自己,提前谢谢你
解决方案
您必须使用数据库外键约束。对于使用 laravel 迁移的 make db,您可以使用
$table->foreign('p_categories_id')
->references('id')->on('p_categories ')
->onDelete('cascade');
见https://laravel.com/docs/5.5/migrations#foreign-key-constraints
推荐阅读
- next.js - what is the best way to deploy nextjs app very first time and after than when a re-deployment is required?
- python - install dtaidistance -> Exception: The compiled dtaidistance C library is not available
- python - How to take Different multi line inputs?
- excel - 如何正确处理错误 91 对象变量或未设置块变量
- html - How do I display an html string in swift with WebKit?
- python - 将 csv 数据转换为特定格式的嵌套 json
- javascript - data.map is not a function in react
- javascript - Jquery Global variable doesn't return value outside the function
- c# - 使用 EntityFrameworkCore + mysql 在 blazor 服务器中“一次性”保存相关表的问题
- javascript - 在反应js中转换日期时间格式