FarbodKain
FarbodKain

Reputation: 229

laravel relationship one to many

before anything ,Highly appreciated in advance for help . i have two model user:

public function posts(){
return $this->hasMany('App\Post');}

post:

public function user(){
return $this->belongsTo('App\user');}

my post have column "user_id" so every post have owner "user_id".

here is my question: i want to delete user but nothing happen to related post. right now i can do this ,but my problem is post_id column have id belongs to deleted user. i want to change that to "null" or "0".

Upvotes: 1

Views: 67

Answers (4)

Sergej Wouldnttell
Sergej Wouldnttell

Reputation: 71

You can do this with SQL power - add a migration to your table "posts" ...

$table->foreign('user_id')
    ->references('id')->on('users')
    ->onDelete('set null');

It will create a foreign key which sets null to related field on deleting user row

Upvotes: 2

z1haze
z1haze

Reputation: 440

You can do this with model events. Something like this on your User model.

public static function boot() {
  parent::boot();

  static::deleting(function($user) {
    $user->posts()->update(['user_id' => null]);
  });
}

Also make sure the user_id field is nullable on the migration.

Upvotes: 2

ettdro
ettdro

Reputation: 350

Just make sure that your post_id field is set to nullable in your migration AND in your database.

Upvotes: 2

Troyer
Troyer

Reputation: 7013

You can change the function boot() from User model:

protected static function boot() {
  parent::boot();

  static::deleting(function($user) {
    $user->posts()->delete();
  });
}

Upvotes: 1

Related Questions