删除具有关系的相关列的最佳方法

kgsdhlau  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(252)

例如,我们有p\u categories表和product表。
p\ U类别表为:

╔═══╦════════════╦═════════════╗
║   ║ 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.); }

我需要用这种方法改变整个项目。因为没有。我正在寻找最好的方法来做到这一点。我写了两个可能的解决方案,但我仍然不知道如何使他们正确。我希望我能解释我自己,提前谢谢你

aemubtdh

aemubtdh1#

必须使用数据库外键约束。对于makedb使用laravel迁移,您可以使用

$table->foreign('p_categories_id')
      ->references('id')->on('p_categories ')
      ->onDelete('cascade');

看到了吗https://laravel.com/docs/5.5/migrations#foreign-关键约束条件

f87krz0w

f87krz0w2#

要在模型中使用有说服力的事件,可以执行以下操作:

static::deleting(function (self $category) {
    $category->products()->delete();
});

如果你也需要在产品上触发事件,你就需要在产品中循环并逐个删除它们。

$category->products->each(function ($product) {
    $product->delete();
});

文档没有显示上述方法,而是倾向于使用 Observers 但是,它确实会显示您可以访问哪些模型事件。

相关问题