首页 > 解决方案 > Laravel DB::raw

问题描述

   Trip::select('trips.id','trips.date_trip',
        DB::raw('(select count(region_id) as count from trip_regions where trip_id=trips.id) as count')
    )->where('count',10)->get();

错误

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'count' in 
'where clause' (SQL: select `trips`.`id`, `trips`.`date_trip`, (select 
count(region_id) as sum from trip_regions where trip_id=trips.id) as 
count from `trips` where `count` = 10)

我有查询行想要 DB::raw。你能帮助我吗???非常感谢

标签: databaselaravellaravel-5.6

解决方案


试试这个 withhaving子句

Trip::select('trips.id','trips.date_trip',
    DB::raw('(select count(region_id) as count from trip_regions where trip_id=trips.id) as count')
)->having('count', '=',10)->get();

您不能where在自定义别名上应用子句,where仅适用于表中存在的列。要过滤掉表达式/聚合结果集的结果,您将需要having子句


推荐阅读