Lets assume i have 3 tables. Students,College and CollegeStudents.
Students table consist of all students (all college students) data.College table consist of all college data. And CollegeStudents table consist of a mapping of Students and College.
Iam not using soft delete.When i delete college, i can easily remove CollegeStudents data by using relationship since CollegeStudents is a child of College.(onDelete('cascade')).
But my problem is ,i want to remove the students from Students table as well when deleting the College row.How come it is possible.is there any way in eloquent to manage this kind of criteria? Advance thanks for your help.
I would suggest using Eloquent's Events for this.
You could start by setting it up in the College model:
Class College extends Model {
public static function boot()
{
parent::boot();
self::deleting(function(College $college) {
// This will fire right before actually deleting the college.
// remove all students from this college
$college->students()->detach();
// I think we might only want to delete students that do not belong to any college anymore right?
Student::doesntHave('colleges')->delete();
// make sure the delete() command is allowed
return true;
});
}
}
I'm making a few assumptions here:
Colleges <--> Students is a belongsToMany relationship, so students can belong to multiple colleges
You delete the students from the college to be deleted, and afterwords only want to delete the colleges that no longer belong to any college (you dont want to delete a student that belongs to 2 colleges by removing one of those colleges)
The relationship on your college model is called students() and on the student model it's called colleges()
Thanks @lostdreamer_nl .But in my situation i have one more table CollegeStudents.That is the problem.I mapped the College table with collegeStudents table.CollegeStudents also mapped with the Students table.
oh, I have the same issue with my table. it's so hard to fix for me, so I even think to ask for help with my college homework this site. but seems like, I've found the solution here. thank you!