在Laravel中使用Eloquent ORM使用'not regexp'执行数据库搜索

时间:2016-10-01 14:30:57

标签: php mysql regex eloquent laravel-5.2

我正在处理按类别搜索类别,我想要排除包含破折号的结果。最后的数字(如:powerbank-1)。 我的问题:

$categories = Category::where('active_products', ">", 0)
    ->where('slug', 'LIKE', "%$search_term%")
    ->where('slug', 'not regexp', "/$search_term-[0-9]/")
    ->get();

我的结果仍包含不需要的结果-1和& slu in中的-2结尾:

{
  "query": "powerbank",
  "categories": [
  {
    "id": 18,
    "parent_id": 17,
    "lft": 108,
    "rgt": 109,
    "depth": 1,
    "name": "Powerbank",
    "description": null,
    "description2": null,
    "products": 43,
    "active_products": 38,
    "created_at": "2016-08-25 20:51:42",
    "updated_at": "2016-09-20 06:06:06",
    "slug": "powerbank"
  },
  {
    "id": 20,
    "parent_id": 19,
    "lft": 124,
    "rgt": 125,
    "depth": 1,
    "name": "Powerbank",
    "description": null,
    "description2": null,
    "products": 43,
    "active_products": 38,
    "created_at": "2016-08-25 20:51:43",
    "updated_at": "2016-09-20 06:06:06",
    "slug": "powerbank-1"
  },
  {
    "id": 22,
    "parent_id": 21,
    "lft": 136,
    "rgt": 137,
    "depth": 1,
    "name": "Powerbank",
    "description": null,
    "description2": null,
    "products": 43,
    "active_products": 38,
    "created_at": "2016-08-25 20:51:43",
    "updated_at": "2016-09-20 06:06:06",
    "slug": "powerbank-2"
  }]
}

1 个答案:

答案 0 :(得分:7)

发现问题为什么不起作用:从正则表达式删除斜杠,所以它将是:

->where('slug', 'not regexp', "$search_term-[0-9]")