Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel hasMany relationship detach all

Is there a simple solution to detach (without deleting) all related models through a hasMany Relation on a model?

For example, I have two tables:

  • College (id, name)

  • Student (id, name, college_id(nullable) )

In the College model I define this relationship:

class College extends Model
{
    public function students()
    {
        return $this->hasMany('App\Student','college_id','id');
    }
}

What is the best way to detach all current College students from the College (i.e, get all the students of the college and set their college_id to null)?

Is there an easy way to detach all students from the College model using eloquent?

Something like

class College extends Model
{
    ...
    public function detachAllStudents()
    {
        ...
    }
}

P.S. already have read this question Laravel hasMany detach, but get errors when I try to apply it to my application

like image 845
Bios90 Avatar asked May 15 '19 18:05

Bios90


1 Answers

Yes, you can detach all the college students as below. Actually, we already have the college_id in your students table and we have to make this college_id null somehow. This is not called detach in Eloquent. The word detach come when you have many to many relationships. So, let's just update the students and see if it works or not.

$college->students()->update(['college_id' => null);

So, you method can be completed as below:

public function detachAllStudents()
{
    $college->students()->update(['college_id' => null]);
}

That's it!

like image 50
Imran Avatar answered Nov 16 '22 12:11

Imran