laravel批量更新问题

时间:2019-01-10 04:58:05

标签: php laravel

我正在尝试在laravel中批量更新我的数据,但是我需要帮助才能在更新方法中找到我的数据ID并进行匹配。

这是我发送的数据的dd结果:

array:5 [▼
  "_method" => "PUT"
  "_token" => "exywo7qYEh69QEZscfxrbiLDzavGdihSLzpeOxlT"
  "title" => "tjd group"
  "vall" => array:7 [▼
    0 => "val 1"
    1 => "val 2"
    2 => "val 3"
    3 => "val 4"
    4 => "val 5"
    5 => "val 6"
    6 => "val 7"
  ]
  "vall_id" => array:7 [▼
    0 => "27"
    1 => "28"
    2 => "29"
    3 => "30"
    4 => "31"
    5 => "32"
    6 => "33"
  ]
]

逻辑

  1. valls是属性(在本例中为tjd组的子组)
  2. vall_id是我发送的每个vall的ID
  3. 我需要将此vall_idvall进行比较,以便更新 我的数据库右行

Blade

{{ Form::model($attribute, array('route' => array('attribute-groups.update', $attribute->id), 'method' => 'PUT', 'files' => true)) }}
<div class="row">
    <div class="col-md-6 mt-20">
        {{Form::label('title', 'Title')}}
        {{Form::text('title', null, array('class' => 'form-control'))}}
    </div>
</div>
@if(count($attribute->values)>0)
<div class="row">
    <div class="col-md-12 mt-20 mb-20"><h4>Values</h4></div>
    @foreach($attribute->values as $value)
    <div class="col-md-4">
        {{Form::label('vall', 'Value')}}
        {{Form::text('vall[]', $value->title, array('class' => 'form-control'))}}
        <input type="hidden" name="vall_id[]" value="{{$value->id}}">
    </div>
    @endforeach
</div>
@endif

    <div class="col-md-6">
        {{Form::submit('Update', array('class' => 'btn btn-success mt-20'))}}
    </div>
</div>
{{Form::close()}}

Controller

public function update(AttributeGroupRequest $request, $id)
{
    $attribute = AttributeGroup::find($id);
    $attribute = AttributeGroup::where('id',$id)->first();
    $attribute->title = $request->input('title');

    // For this part i need help
    //vall , val_id
    if($attribute->save()){
        $attribute_id = $attribute->id;
        if ($request->has('vall')){
          foreach($request->vall as $val) {
            Attribute::update([
            'title' => $val,
            'attribute_id' => $attribute_id,
            ]);
          }
        }
    }
    //

    Session::flash('success', 'Attribute Group, '. $attribute->title.' updated successfully.');
    return redirect()->route('attribute-groups.index', $attribute->id);
}

任何人都可以帮助解决此问题吗?

2 个答案:

答案 0 :(得分:5)

只需使用array_combine组合ID和值即可。

$valls = array_combine($request->vall_id, $request->vall);
foreach($valls as $vall_id => $val) {
    Attribute::where('id', $vall_id)
        ->update([
            'title' => $val,
            'attribute_id' => $attribute_id,
        ]);
}

答案 1 :(得分:0)

您错过了where子句。这样做:

if($attribute->save()){
    $attribute_id = $attribute->id;
    if ($request->has('vall')){
      $vall_ids = $request->vall_id;
      foreach($request->vall as $key => $val) {
        Attribute::where('id', $vall_ids[$key])->update([
        'title' => $val,
        'attribute_id' => $attribute_id
        ]);
      }
    }
}