【问题标题】:Get all IDs that I selected from multiple select box and update another table - laravel获取我从多个选择框中选择的所有 ID 并更新另一个表 - laravel
【发布时间】: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


【解决方案1】:

WhereIn 接受一个数组

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

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

所以它会变成

->whereIn('id', $bins)

【讨论】:

    【解决方案2】:

    你可以这样做:

    $bins = Bin::whereIn('id', request('bins'))->get();
    

    whereIn 方法接受一个数组作为第二个参数 look here

    【讨论】:

    • 这也很好用,只需传入请求即可
    • 太棒了!随时!
    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 2017-11-06
    • 2013-09-05
    • 2017-11-13
    • 2023-03-22
    • 2011-03-30
    • 2014-12-16
    • 2016-11-30
    相关资源
    最近更新 更多