php 查询 Laravel 选择 WhereIn 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38159729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:30:50  来源:igfitidea点击:

Query Laravel Select WhereIn Array

phplaraveleloquent

提问by Do Thanh Dat

This query does not work correctly, it only shows 1 row

此查询无法正常工作,它只显示 1 行

 $data = Post::select('id', 'name')
   ->whereIn('id', [$order])
   ->orderByRaw(\DB::raw("FIELD(id, $order)"))
   ->get();

but this works fine, it shows all rows

但这工作正常,它显示所有行

  $data = Post::select('id', 'name')
    ->whereIn('id', [1,2,3])
    ->orderByRaw(\DB::raw("FIELD(id, $order)"))
    ->get();

Thank you!

谢谢!

回答by Rakesh Kumar

Your Query is Here:-

您的查询在这里:-

$data = Post::select('id', 'name')
  ->whereIn('id', $order)
  ->orderByRaw(\DB::raw("FIELD(id, ".implode(",",$order).")"))
  ->get();

Remove []from $order.

删除[]$order

For WhereIncondition second parameter should be an array. So the $ordershould be

对于WhereIn条件,第二个参数应该是一个数组。所以$order应该是

$order = [1,2,3,4]

回答by D.Dimitrioglo

If your $orderis an array, i think that you should do this

如果你$order是一个数组,我认为你应该这样做

whereIn('id', $order)instead of whereIn('id', [$order])

whereIn('id', $order)代替 whereIn('id', [$order])

P.S. In official documentation mentioned that second argument should be an array:

PS 在官方文档中提到第二个参数应该是一个数组:

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