首页 > 解决方案 > 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_idvall是我发送的每个人的 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);
}

任何人都可以帮助解决这个问题?

标签: phplaravel

解决方案


只是array_combine用来组合 ids 和 values。

$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,
        ]);
}

推荐阅读