简体   繁体   中英

Using Eloquent ORM in Laravel to perform search of database using 'not regexp'

I'm dealing with searching in categories by slug and I want to exclude results which contain dash & number at the end (like: powerbank-1). My query :

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

My result still contain unwanted results with -1 & -2 endings in slug:

{
  "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"
  }]
}

发现了为什么不起作用的问题:从正则表达式中删除斜杠,因此它将是:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM