在laravel where子句中使用find_in_set()

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在laravel where子句中使用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。

我哪里错了?

答案

我看到您当前代码存在的几个潜在问题。首先,你应该将$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();

以上是关于在laravel where子句中使用find_in_set()的主要内容,如果未能解决你的问题,请参考以下文章