Reputation: 537
My question is related to Laravel 5.6. I have Post
and Category
models. They have one-to-many relationship, with category_id
as foreign key in posts
table. The category_id
is nullable field
//Post Model
class Post extends Model
{
public function category()
{
return $this->belongsTo('App\Category', 'category_id', 'id');
}
}
//Category Model
class Category extends Model
{
public function posts()
{
return $this->hasMany('App\Post', 'category_id', 'id');
}
}
My question is, If I delete a category. How do I set category_id
to null for all the associated posts in posts
table ?
I know laravel provide dissociate
method, but I think it is for belongsTo
relationship. Is there something similar to below?
$category::find($id);
$category->posts()->dissociate(); //set all foreign key(category_id) to null in posts table
$category->delete();
Upvotes: 1
Views: 2365
Reputation: 25906
You don't want to take care of this yourself, let the foreign key handle it (as suggested by CD001):
Schema::create('posts', function (Blueprint $table) {
[...]
$table->foreign('category_id')->references('id')->on('categories')
->onDelete('set null');
});
Upvotes: 4