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"
]
]
逻辑
valls
是属性(在这种情况下,我的组的孩子 tjd 组)vall_id
vall
是我发送的每个人的 id- 我需要将其
vall_id
与vall
更新数据库中的正确行进行比较
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);
}
任何人都可以帮助解决这个问题?
解决方案
只是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,
]);
}
推荐阅读
- python - 检查目标时出错:预期 activation_5 的形状为 (1,) 但得到的数组的形状为 (2,)
- c - 在链表中使用 malloc 后的 Free()
- android - 如何在 RecyclerView Kotlin 中添加 Header
- azure - 我是否应该使用 Google Cloud Function 或 App Engine 来连接 Azure 认知服务并获得快速结果?
- apache-spark - How to modify a dataframe in-place so that its ArrayType column can't be null (nullable = false and containsNull = false)?
- javascript - 如何在reactjs中将逗号分隔符放在数字类型的输入字段中?
- haskell - Haskell Data.Unique
- javascript - 自动调整多个文本区域的高度以适应加载的内容
- html - 图片元素 - 标题属性
- java - 如何从 Dialog RecyclerView 获取数据到其托管活动?