【问题标题】:Invalid argument supplied for foreach() laravel using whereIn (laravel 5.3)使用 whereIn (laravel 5.3) 为 foreach() laravel 提供的参数无效
【发布时间】:2017-06-06 07:47:07
【问题描述】:

我在我的控制器中使用 jquery 获取 ids

if(!empty($request->input('ids'))) {
    $ids = $request->input('ids');
    }else{
                $ids = null;
            }

我试试dd($ids)

输出和我的控制台一样

array:3 [
  0 => "1"
  1 => "2"
  2 => "on"
]

当我将 ids 传递给我的查询时

查询

$student_ids = DB::table('students')
             ->orderBy('name', 'asc')
              ->where('group_id', '<>', 0)
              ->whereIn('students.id','=', $ids)
              ->pluck('id');

它不工作

错误是:为 foreach 提供的参数无效

请帮助我哪里错了。谢谢

【问题讨论】:

  • 如何在视图中获取 id? 3.数组“on”中的元素应该存在吗?我认为那里有问题。
  • 为什么你的 id 是字符串?
  • if($request->has('ids'))) {}
  • 你的 foreach 实际上在哪里?
  • ->whereIn('students.id', $ids) - 更多信息请查看laravel.com/docs/5.4/queries

标签: php mysql laravel


【解决方案1】:

你应该改变这个:

->whereIn('students.id','=', $ids)

到这里:

->whereIn('students.id', $ids)

因为第二个参数应该是可迭代的 ID,但您传递的是字符串 =。另外,请确保您传递的是一个数组或 ID 集合。

【讨论】:

    【解决方案2】:

    变化:

    where('students.id', '=', $ids)
    

    收件人:

    whereIn('students.id', $ids);
    

    【讨论】:

    • 还是同样的问题
    • @bluemoon 仔细看……你仍在使用= 作为whereIn 的第二个参数。但是,whereIn 不接受比较运算符作为第二个参数,它只接受一个数组作为第二个参数。完全使用我上面发布的内容。
    【解决方案3】:

    像其他人提到的那样更新whereIn 参数。还可以像这样简化您的请求输入。

    $ids = $request->input('ids', []);
    
    $student_ids = DB::table('students')
        ->orderBy('name', 'asc')
        ->where('group_id', '<>', 0)
        ->whereIn('students.id', $ids)
        ->pluck('id');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 2018-12-09
      • 1970-01-01
      • 2015-06-29
      • 2022-01-27
      • 2018-02-26
      • 2017-11-26
      相关资源
      最近更新 更多