2015-06-08 75 views
2

我被困在更新具有「hasMany」關係的eagerloaded模型。Laravel更新相關模型與推?

我有一個模型,如下所示:

class UserGroup extends Model 
{ 

    public function enhancements() 
    { 
    return $this->hasMany('App\UserGroupEnhancement'); 
    } 

} 

我控制器傳遞$ userGroup表示的觀點,像這樣:

$userGroup = $this->userGroup->with('enhancements')->whereId($id)->first(); 

,然後在我看來,我有

@foreach($userGroup->enhancements as $enhancement) 

    <label>{{$enhancement->type}}</label> 
    <input class="form-control" name="enhancements[{{$enhancement->id}}][price]" value="{{$enhancement->price}}"> 

    @endforeach 

更新時,如何更新增強關係中的所有記錄?它被傳回到多個數組中。我目前正在做這樣的事情。

public function update($id) 
{ 
    $userGroup = $this->userGroup->findOrFail($id); 
    $enhancement = \Input::get('enhancements'); 
    if (is_array($enhancement)) { 
     foreach ($enhancement as $enhancements_id => $enhancements_price) { 
      $userGroup->enhancements()->whereId($enhancements_id)->update($enhancements_price); 
     } 
    } 
} 

有沒有一種方法可以做到這一點,而無需foreach循環?我看到了push()方法,但似乎只適用於單個數組。

回答

1

沒有更好的方法來做到這一點。有一種稱爲saveMany的Eloquent方法,但它用於創建新記錄而不更新。例如Doc

$comments = [ 
    new Comment(['message' => 'A new comment.']), 
    new Comment(['message' => 'Another comment.']), 
    new Comment(['message' => 'The latest comment.']) 
]; 

$post = Post::find(1); 

$post->comments()->saveMany($comments); 

我會堅持自己的解決方案,你甚至可以創建一個特質或基口才類,並把該邏輯的方法,因此它可以被所有其他機型上使用,如果你需要。 喜歡的東西:

trait UpdateMany { 

    public function updateMany($updates, $relationshipName) 
    { 

     if (!empty($updates)) { 
      foreach ($updates as $update_id => $update) { 
       $this->{$relationshipName}()->whereId($update_id)->update($update); 
      } 
     } 

    } 
} 

然後連接到你的模型(S):

class UserGroup extends Model 
{ 

    use UpdateMany; 

    public function enhancements() 
     { 
     return $this->hasMany('App\UserGroupEnhancement'); 
     } 

} 

,只需爲使用:

$userGroup = $this->userGroup->findOrFail($id); 
$userGroup->updateMany(\Input::get('enhancements'), 'enhancements'); 
+0

感謝。在我的基地回購中使用updateMany方法將工作。我幾個小時以來一直在努力,認爲有一些推動方法可以完成這項任務。 – limit