首页 > 解决方案 > 删除具有关系的相关列的最佳方法

问题描述

例如,我们有 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 个可能的解决方案,但我仍然不知道如何正确地制作它们。我希望我能解释一下自己,提前谢谢你

标签: mysqldatabaselaravelmodelrelationship

解决方案


您必须使用数据库外键约束。对于使用 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


推荐阅读