【问题标题】:Laravel DB::rawLaravel DB::raw
【发布时间】:2018-10-24 07:02:44
【问题描述】:
   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。你能帮助我吗???非常感谢

【问题讨论】:

    标签: database laravel laravel-5.6


    【解决方案1】:

    having 子句试试这个

    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 子句

    【讨论】:

    • ->whereBetween('count',[$date, $date_today])
    • 如果它在中间
    • @UlasoftKoinotUz 我不明白你的意思是检查一个数字是否在一个日期范围内?您也可以使用havingRaw() 来进行原始查询/语句,看看laravel.com/docs/5.6/queries
    • ->whereBetween('count',[$min, $max])
    • @UlasoftKoinotUz 你可以用havingRaw 来写你的表达式,比如havingRaw('count between '. $min.' and '. $max)
    猜你喜欢
    • 2019-01-10
    • 2015-03-26
    • 2016-07-29
    • 2019-08-20
    • 2014-12-05
    • 2017-11-17
    • 2021-03-02
    • 2019-02-27
    • 1970-01-01
    相关资源
    最近更新 更多