【问题标题】:Laravel: whereIn with variableLaravel:带有变量的whereIn
【发布时间】:2018-07-03 09:34:48
【问题描述】:

我正在尝试在变量 $sections 中收集属于发生在他们身上的部分的所有记录。但只有第 1 节的人接我。有什么建议吗?

$sections = '1,2,3';

$data = News::where('active', '1')
        ->whereIn('section_id', [$sections])
        ->get();

如果我将查询中的 $sections 替换为值,这是可行的,但如果我使用变量 $sections,它就不起作用了。

谢谢。

【问题讨论】:

    标签: php sql database laravel where-in


    【解决方案1】:

    您的 $sections 变量是一个字符串。而且您将该字符串传递给数组,而不是字符串中的每个单独的数字。

    例如:

    $users = DB::table('users')
                    ->whereIn('id', [1, 2, 3])
                    ->get();
    

    【讨论】:

      【解决方案2】:

      当你使用whereIn() 时,你必须传递一个数组而不是字符串:

      $sections = explode(',', '1,2,3');
      

      【讨论】:

      • 他最好 $sections = [1,2,3];
      • @Amarnasan 这只是一个例子。我不认为 OP 对这些类别进行硬编码,而是从请求中将它们作为字符串或其他内容获取。
      • Amarnasan,我按照您之前指出的方式进行了尝试,但我只从第一部分得到了这些。 Alexey 的回答是正确的
      猜你喜欢
      • 2018-07-01
      • 1970-01-01
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      相关资源
      最近更新 更多