2016-04-22 92 views
0

我在Laravel 5.1中有一個應用程序,其中安裝了以下表格;Laravel 5.1刪除行時刪除子關係數據

  • 時間表
  • day_total
  • segment_totals

行屬於時間表。 日總計屬於時間表。 段總計屬於行。

當時間表被刪除時,我也希望它從rowday_totalsegment_total刪除行以及來自timesheet表本身的行。

我已經在我的timesheet模型中設置了以下引導方法;

/** 
* Boot the model. 
* 
*/ 
public static function boot() 
{ 
    parent::boot(); 

    static::deleting(function($timesheet) 
    { 
     $timesheet->row()->delete(); 
     $timesheet->dayTotal()->delete(); 
    }); 
} 

我在row模型中設置了以下內容;

/** 
* Boot the model. 
* 
*/ 
public static function boot() 
{ 
    parent::boot(); 

    static::deleting(function($row) 
    { 
     $row->day()->delete(); 
     $row->segmentTotal()->delete(); 
    }); 
} 

當時間表被刪除,rowdayTotal行被刪除,但daysegmentTotals不會被刪除。我怎樣才能讓Laravel在row模型上觸發刪除?

+0

你可以請發表你的實體和關係,因爲它似乎有問題的型號是在MYSQL中彼此沒有關係? – Cowwando

回答

0

當您在關係查詢上調用delete()時,它會針對數據庫運行直接查詢以刪除記錄。因此,相關模型不會加載,並且無法調用這些模型上的事件deleting。您需要以可以調用相關模型上的事件的方式刪除記錄。

您可能需要遍歷相關模型,並呼籲delete()每個模型實例,或者你可以得到相關的ID列表,然後使用destroy()方法(這只是加載模型每個ID,並調用delete()在上面)。

選項1:循環通過相關模型

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

    static::deleting(function($timesheet) 
    { 
     foreach($timesheet->row()->get() as $row) { 
      $row->delete(); 
     } 
     foreach($timesheet->dayTotal()->get() as $dayTotal) { 
      $dayTotal->delete(); 
     } 
    }); 
} 

選項2:使用destroy()與IDS:

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

    static::deleting(function($timesheet) 
    { 
     // getRelated() method gets the related model from the relationship. 
     // This is so you don't have to hardcode \App\Row::destroy() 
     // or \App\DayTotal::destroy() 

     $ids = $timesheet->row()->lists('id')->all(); 
     $timesheet->row()->getRelated()->destroy($ids); 

     $ids = $timesheet->dayTotal()->lists('id')->all(); 
     $timesheet->dayTotal()->getRelated()->destroy($ids); 
    }); 
}