2017-07-09 130 views
0

我有2個表和三個關係,在laravel enquent中保存嵌套關係?

第一,獎賞表,

click to see award table structure

獎標準,

click to see criteria table structure

以下標準表自加盟,

在數據庫中儲存獎勵時,

現在我保存如下,

$award->save(); 
foreach ($request->criterias as $key => $row) { 
      $criteria = new AwardCriteria(); 
      $criteria->title = $row['title']; 
      $criteria->mark = $row['mark']; 
      $criteria->save(); 
      foreach ($row['sub_criterias'] as $row2) { 
       $subCrt = new AwardCriteria(); 
       $subCriteria->award_id = $award->id; 
       $subCriteria->award_criteria_id = $criteria->id; 
       $subCrt->title = $row2['title']; 
       $subCrt->mark = $row2['mark']; 
       $subCrt->save(); 
      } 
     } 

我能做到這樣也

$award->save(); 
    $award->criteria()->saveMany($criteria); 

但這裏如何保存子critirea的?你能請任何人提出好的方法嗎?

回答

0

您實際上可以偵聽在模型上保存事件並觸發操作。這個post有一些很好的例子。