Reputation: 3
I have 4 tables as below:
class Job extend Model
{
public function candidates()
{
return $this->hasMany(App\Models\Candidate::class);
}
}
=========================================================
class Candidate extend Model
{
public function skills()
{
return $this->belongsToMany(App\Models\Skill::class);
}
public function job()
{
return $this->belongsTo(\App\Models\Job::class);
}
}
So, when I delete a job. I want to delete all candidates who apply to this job also. But, When I delete I got this message
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`evaluation_db`.`candidate_skill`, CONSTRAINT `candidate_skills_candidate_id_foreign` FOREIGN KEY (`candidate_id`) REFERENCES `candidates` (`id`)) (SQL: delete from `candidates` where `candidates`.`job_id` = 39 and `candidates`.`job_id` is not null)
I think, it because of skills relation inside candidate class. Could any one help me out? I really appreciate with your help.
Thank you!
Upvotes: 0
Views: 5061
Reputation: 95
Delete all customers (children) when deleting company (parent)
$companyDetails = Company::find($companyId);
if (!$companyDetails) {
return "Company Not Found.";
}
$companyDetails->customers()->delete();
$companyDetails->delete();
Upvotes: 1
Reputation: 2390
You need to define the behaviour in your migration.
Doc : https://laravel.com/docs/8.x/migrations#foreign-key-constraints
$table->foreignId('user_id')
->constrained()
->onUpdate('cascade')
->onDelete('cascade');
Upvotes: 2