在Laravel原始查询中,使用where in和逗号分隔的值只返回一行



我正在使用Laravel 5.2开发一个php项目。在我的应用程序中,我使用手动查询从数据库中检索记录。但我在使用带有csv的where语句检索记录时遇到了问题。

示例我如何检索

$csv = "1,3,5";
$sql = "SELECT * FROM `items` WHERE `id` IN (?)";
$rows = DB::select($sql,[$csv]);

正如您在上面看到的,我正在检索三行。但它只返回一行,其中id为1。为什么?

你不能那样做。csv中的每个条目都是一个单独的参数,因此对于您的代码,您实际上需要IN (?, ?, ?),然后传入值数组。编写代码可以很容易地做到这一点(将字符串分解为一个数组,创建另一个相同大小的问号数组,然后将其放在一起)。

然而,您使用的是Laravel,因此使用Laravel为您提供的功能会更容易。

使用查询生成器,您可以这样做:

$csv = "1,3,5";
// turn your csv into an array
$ids = explode(",", $csv);
// get the data
$rows = DB::table('items')->whereIn('id', $ids)->get();
// $rows will be an array of stdClass objects containing your results
dd($rows);

或者,如果您为items表设置了Item模型,您可以执行以下操作:

$items = Item::whereIn('id', $params)->get();
// $items will be a Collection of Item objects
dd($items);

或者,假设id是项目表的主键:

// find can take a single id, or an array of ids
$items = Item::find($params);
// $items will be a Collection of Item objects
dd($items);

编辑

如果你真的想用手动的方式,你可以使用循环,但你不需要。PHP提供了一些非常方便的数组方法。

$csv = "1,3,5";
// turn your csv into an array
$ids = explode(",", $csv);
// generate the number of parameters you need
$markers = array_fill(0, count($ids), '?');
// write your sql
$sql = "SELECT * FROM `items` WHERE `id` IN (".implode(',', $markers).")";
// get your data
$rows = DB::select($sql, $ids);

相关内容

最新更新