[英]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.php和Post.php
public function category()
{
return $this->belongsTo('App\Post', 'category_id');
}
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.