首页 > 解决方案 > Laravel 查询构建器,使用包含和排除进行过滤

问题描述

我在查询中遇到了一些特定的包含/排除逻辑的问题。

餐桌篮子有很多特定的水果。Specific_fruits 有正则表达式,并且有一个包含或排除的字段。

specific_fruit 表列:
'LOGIC'、'REGEX'

条目:
“包括”、“苹果”、
“排除”、“梨”

首先,我将所有带有“apple”一词的字符串都包括在内。这可以正常工作。但是,在那之后,我想排除所有也有“梨”这个词的水果串。

例如:
'apple banana' 应该包含
'apple pear' 不应该。

包括正常工作。正则表达式工作正常。当查询被排除时..它仍然返回已经包含的篮子。

已经“包含”在第一个 WHERE 函数中的篮子需要以某种方式排除。

DB::table('examples')
   ->join('baskets', 'examples.basket_id', 'baskets.id')
   ->leftJoin('specific_fruit', 'specific_fruit.baskets.id', 'baskets.id')
   ->where(function($query) use ($request) {
       $query->where('specific_fruit.logic', 'include') // we're including these
           ->whereRaw('? ~ specific_fruit.regex', ['apple pear']) // we want to include all "apple" 
           ->orWhere('specific_fruit.logic', 'exclude') // grab all excluded fruit for now, we'll purge the ones next step
   })
   ->where(function($query) use ($user_data, $request) {
       $query->where('specific_fruit.logic', 'include') // retain the included fruit from the previous query
           ->orWhere('specific_fruit.logic', 'exclude') // when we exclude these, it's not removing the ones that are already "included"
           ->whereRaw('? !~ specific_fruit.regex',['apple pear']) // if regex DOES NOT match (!~), exclude that basket
   })

标签: phplaravelpostgresqllaravel-query-builder

解决方案


推荐阅读