【发布时间】:2017-08-24 21:39:48
【问题描述】:
我有一个表单,用户可以在其中从选择框中选择多个标签。然后我需要创建货件,然后,我需要获取用户从标签中选择的所有 ID,并更新另一个表,其中 ID 与用户选择的标签 ID 匹配。
这里是选择框:
<select name="bins[]" class="form-control" id="shipping_bin_labels_select" multiple="multiple">
@foreach(\App\Bin::all() as $bin)
<option value="{{ $bin->id }}" {{ old('bins') }}>{{ $bin->label }}</option>
@endforeach
</select>
这是它的外观:
然后我创建货件:
public function store(Request $request)
{
$this->validate($request, [
'truck' => 'required',
'bins' => 'required',
'stand_id' => 'required',
]);
$standName = request('stand_id');
$standName = Stand::where('name', '=', $standName)->first();
Shipment::create([
'truck' => request('truck'),
'stand_id' => $standName->id
])->save();
...........
之后,我需要遍历所有 bin 标签,获取它们的 ID,并使用我刚刚创建的货件 ID 更新“bins”表。我不知道如何使用我刚刚选择的 bin ID 从 bins 表中获取所有 bin。
这是我迄今为止尝试过的:
$bins = $request->input('bins');
$bins = implode(',', $bins);
// Tried this, but get empty collection. [$bins] (brackets) dont help either.
$bins = Bin::whereIn('id', $bins)->get();
// Tried this, but get "Call to a member function all() on string"
$bins = Bin::whereIn('id', $bins->all())->get();
// This is what I sort of need
$bins = Bin::whereIn('id', [3, 5, 6])->get();
作为参考,当我 DD 时:
$bins = $request->input('bins');
$bins = implode(',', $bins);
dd($bins);
我明白了:
这些是我在选择框中的 bin ID。不用担心 ID 字符串很长,我的 ID 就是这样格式化并存储在 bins 表中的。
【问题讨论】:
-
在哪里接受一个数组,所以之前不要内爆垃圾箱。
-
让我看看,1 秒
-
哦,天哪,太复杂了,只需要删除 implode 。回答问题,以便我给你信用
-
我以前做过这样的事情:-)
标签: php laravel laravel-5.4