简体   繁体   English

从一对多关系中删除 Laravel

[英]Deleting from One-to-Many relationship Laravel

I have the two following models in one to many relationship:我在一对多关系中有以下两个模型:

Category.php分类.php

public function post()
{
    return $this->hasMany('App\Category', 'category_id');
}

And Post.phpPost.php

public function category()
{
    return $this->belongsTo('App\Post', 'category_id');
}
  1. I delete thee category that has few blog post under it.我删除了其下几乎没有博客文章的类别。
  2. Open the blog post whose category is deleted打开类别被删除的博文
  3. Gets error as the category doesn't exist anymore获取错误,因为该类别不再存在

What is the best way to delete the category without causing the error ?在不导致错误的情况下删除类别的最佳方法是什么? Should I set the category_id of post to null while deleting their category ?我应该在删除他们的category_id将 post 的category_id设置为null吗?

Use withDefault for if any category doesn't exist it'll give you null.使用withDefault如果任何类别不存在,它会给你空。

Category.php分类.php

public function post()
{
    return $this->hasMany('App\Post', 'category_id')->withDefault();
}

Post.php后.php

public function category()
{
    return $this->belongsTo('App\Category', 'category_id')->withDefault();
}

Maybe this is gonna be the late answer but I will answer for Google searches anyway.也许这将是迟到的答案,但无论如何我都会回答谷歌搜索。

You can handle relationship cascading on the database If you don't want any null error about deleting the models on your project.如果您不希望在删除项目上的模型时出现任何空错误,您可以处理数据库上的关系级联。 Write this code to your project table migration.将此代码写入您的项目表迁移。

$table->bigInteger('category_id')->unsigned();
$table->foreign('category_id')->references('id')
      ->on('categories')->onDelete('cascade');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM