mercredi 12 septembre 2018

Set Foreign Key to Null in One to Many Relationship in Laravel 5

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();



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2CZwur9
via IFTTT

Aucun commentaire:

Enregistrer un commentaire