2015-06-08 29 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