php - 获取我从多个选择框中选择的所有 ID 并更新另一个表 - laravel

标签 php laravel laravel-5.4

我有一个表单,用户可以在其中从选择框中选择多个标签。然后我需要创建发货,在我这样做之后,我需要获取用户从标签中选择的所有 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>

这是它的样子:

enter image description here

然后我创建发货:

  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);

我明白了:

enter image description here

这些是我在选择框中的垃圾箱 ID。不要担心长 ID 字符串,这就是我的 ID 的格式和存储在 bins 表中的方式。

最佳答案

WhereIn 接受一个数组

->whereIn('id', [1, 2, 3])

如果删除内爆,则可以将该数组传递到查询中。

所以会变成

->whereIn('id', $bins)

关于php - 获取我从多个选择框中选择的所有 ID 并更新另一个表 - laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45862956/

相关文章:

php - 来自另一个数据库的 MySQL 子查询,其中表名取决于主查询

php - Flash Builder/php/mysql 函数

php - 带有额外参数的策略

php - Laravel 自定义验证消息作为数组导致错误

php - Windows 10 WSL ZipArchive::extractTo(): 权限被拒绝 Laravel

javascript - Vuejs 2.4.4 + Laravel 5.5 渲染来自 api 调用的响应

php - 保持表示 (HTML) 和逻辑 (PHP) 分离

php - 如何让网站访问者安装 Chrome

javascript - 从 javascript 获取输入值时无法将值传递给 Controller

Laravel Spark : CSRF Failure on Login Page