laravel批量更新问题

maf*_*tis 0 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"
  ]
]
Run Code Online (Sandbox Code Playgroud)

逻辑

  1. valls 是属性(在这种情况下tjd组中我的组的子项)
  2. vall_idvall我发送的每个人的身份
  3. 我需要比较这vall_idvall为了我DATABSE更新右排

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()}}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙解决这个问题吗?

小智 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,
        ]);
}
Run Code Online (Sandbox Code Playgroud)