在Laravel where子句中使用find_in_set()

时间:2019-04-18 06:23:56

标签: laravel find-in-set

我知道我可以使用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。

我要去哪里错了?

1 个答案:

答案 0 :(得分: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();