如何通过HAVING和MAX对Group by进行雄辩的查询

时间:2019-03-31 13:25:24

标签: laravel laravel-5 eloquent

我有需要转换为Eloquent的SQL查询,也不知道在哪里写MAX条件。没有太多原始sql怎么转换它?谢谢!

SELECT bike_id
FROM bike_filters
GROUP BY bike_id
HAVING
   MAX(bike_category_id in (416,11111)) = 1
   AND MAX(bike_category_id in (5555,779)) = 1
   AND MAX(bike_category_id in (5555,772)) = 1

表结构:

| id | bike_id | bike_category_id |
| 1  | 3       | 416              |
| 2  | 3       | 779              |
| 3  | 3       | 344              |
| 4  | 3       | 332              |
| 5  | 4       | 444              |
| 5  | 5       | 555              |

此查询的目的是获取bike_id,该查询具有查询的所有参数-自行车可以具有20个过滤器,但是如果用户按5进行搜索并且自行车与之匹配,则此查询将获得bike_id。

1 个答案:

答案 0 :(得分:0)

为此,您可以使用havingRaw(),其外观类似于:

$query = DB::table('bike_filters')
    ->select('bike_id')
    ->groupBy('bike_id')
    ->havingRaw('MAX(bike_category_id in (416,11111)) = 1')
    ->havingRaw('MAX(bike_category_id in (5555,779)) = 1')
    ->havingRaw('MAX(bike_category_id in (5555,772)) = 1')
    ->get();