【问题标题】:laravel eloquent join where clause with sub query to use column name comparision not workinglaravel eloquent join where 子句与子查询以使用列名比较不起作用
【发布时间】:2021-09-15 19:10:11
【问题描述】:

我在使用 laravel eloquent join 来比较 where 子句中的日期时遇到问题。下面的查询给了我错误未知列policy_periods.statecode 我在连接子查询的 where 子句中使用此列,例如 App\Elrd::where("state_code",'=',DB::raw (policy_periods.statecode))->where('date',"max('date')

如果可能有任何解决方案,您能给我一个想法吗? 我已经尝试过 whereRaw,whereColumn 但它们都不起作用。

 DB::table('policy_periods')
                 ->join('payrolls','payrolls.policy_period_id', '=', 'policy_periods.id')
                 ->leftjoin('elrds', function($join) use($mod_rating_eff_date)
                 {
                    $join->on('elrds.state_code', '=', 'policy_periods.statecode');
                    $join->on('elrds.class_code', '=', 'payrolls.code');                  
                    $join->where('elrds.date',App\Elrd::where("state_code",'=',DB::raw(`policy_periods`.`statecode`))->where('date',"<=",$mod_rating_eff_date)->max('date'));
                    
                 })                
                 ->select('payrolls.*','payrolls.elr as payrollelr','policy_periods.id as pid','policy_periods.policy_no',DB::raw('CONCAT(eff_date, "-", exp_date) as dateGroup'),'policy_periods.eff_date','policy_periods.exp_date','policy_periods.statecode as ratingeffPolicyYear','policy_periods.statecode','elrds.class_code','elrds.year','elrds.date','elrds.elr','elrds.dratio')                 
                 ->where('policy_periods.mod_id',$id)             
                 ->get();

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    当我遇到这样的问题时,我通常做的第一件事就是确定生成的查询是否是我想要的。 您应该记录您的查询,以便确保它。 为此,一种可能的解决方案是在您的 AppServiceProvider 中添加一个日志(在函数启动中):

    DB::listen(function ($query) {
        Log::debug('query',[
            $query->sql,
            $query->bindings,
            $query->time
        ]);
    });
    

    话虽如此,这些反引号是从哪里来的?

    DB::raw(`policy_periods`.`statecode`)
    

    你可以用DB::raw('policy_periods.statecode')替换它

    请告诉我它是否解决了您的问题,或者如果问题没有解决,请提供生成的 SQL 查询。

    【讨论】:

    • 嗨,感谢您的反馈,但我尝试与您提供的相同,但仍然收到错误 Unknown column 'policy_periods.statecode' in 'where Clause' mysql 查询显示:select max(date) as aggregate from @ 987654325@ 其中state_code = policy_periods.statecode 和date
    • 好的,那么我们至少知道发生错误是因为查询被 Eloquent 拆分为 2 个查询。
    • 它来自App\Elrd::where(中引入的“where”语句。尝试简化连接子句:看起来很复杂。
    • 抱歉,请您指导我解决方案,因为如果我删除导致错误的 where 条件,我的查询将完美运行。只需要更正where条件即可
    • 也许,首先在您的联接中“where”子句的目的是什么?同一行有 3 个不同的“位置”,这很难理解。
    猜你喜欢
    • 2017-01-31
    • 2021-12-27
    • 1970-01-01
    • 2017-08-24
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多