简体   繁体   中英

Laravel delete related records

I've got 1 company. That company hasMany departments. When I want to softdelete company the departments should be softdeleted aswell. Right now I'm doing that like this:

Company.php

protected static function boot()                         
{                                                        
    parent::boot();                                      
    static::deleting(function($company) {                
        foreach($company->department as $department)     
        {                                                
            $department->delete();                       
        }                                                
    });                                                  
}   

But for some reason only the first department is beeing softdeleted while the company has for example 17 departments.

What am I doing wrong??? I'm looking for hours right now still no solution!

--EDIT--

A department hasMany Employees.

protected static function boot()
    {
        parent::boot();
        static::deleting(function($department) {
            Employee::where('DepartmentId','=',$department->DepartmentId)->delete();
        });
    }       

Try this:

$departmentID[] = Department::where('company_id', '=', $company->id)->select('id')->distinct()->get()->toArray();
Department::where('company_id', '=', $company->id)->delete();

DB::table('users')->whereIn('department_id', $departmentID)->delete();

See, if that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM