在laravel where子句中使用find_in_set()

问题描述 投票:1回答:1

我知道我可以使用find_in_set如下:

select `id` from `questions` where FIND_IN_SET(8, categories);

但我正在使用laravel,我想在那里写这个查询。我试过这个:

$q_category = 8;
$object = DB::table("questions")
  ->select('id')
  ->where(DB::RAW("FIND_IN_SET($q_category, categories)"), '!=', null)
  ->get();

获取8列中包含categories的记录(其中包含逗号分隔的类别ID)

但我得到的记录也没有类别ID。

我哪里错了?

laravel find-in-set
1个回答
2
投票

我看到您当前代码存在的几个潜在问题。首先,你应该将$q_category值绑定到对FIND_IN_SET的调用。其次,成功调用FIND_IN_SET的检查是返回值大于零,而非NULL

$q_category = 8;
$object = DB::table("questions")
    ->select('id')
    ->whereRaw("FIND_IN_SET(?, categories) > 0", [$q_category])
    ->get();
© www.soinside.com 2019 - 2024. All rights reserved.