dtyyrt4545 2018-12-13 18:42
浏览 82

Eloquent - 如何在更多条件下使用别名?

In continuation to the question in the thread MYSQL How to perform custom month difference between two dates in MYSQL?, I tried to join the allowed_exp_range table only on condition with the derived "exp_in_months" result along with few other conditions. Below are the details.

table_name = "user"
id | name | join_date 
---------------------
1| Sam | 25-11-2017
2| Moe | 03-04-2017
3| Tim | 04-07-2018
4| Sal | 30-01-2017
5| Joe | 13-08-2018


//$user_query is the eloquent query after chaining different other conditions 
$user_query = $user_query->select(DB::raw("id, name , (YEAR(CURDATE())*12+MONTH(CURDATE())) - (YEAR(STR_TO_DATE(join_date, '%d-%m-%Y'))*12+MONTH(STR_TO_DATE(join_date, '%d-%m-%Y'))) - 1 -- whole months
           + CASE WHEN DAY(LAST_DAY(STR_TO_DATE(join_date, '%d-%m-%Y'))) - DAY(STR_TO_DATE(join_date, '%d-%m-%Y')) + 1 + DAY(CURDATE()) > 15 THEN 1 ELSE 0 END -- broken month
           AS exp_in_months)

table_name: "allowed_exp_range"
starting_exp_months | end_exp_months | category_id
--------------------------------------------------
0 | 6 | 1
9 | 24 | 1
11 | 50 | 2
100 | 150 | 2


if ($exp_based_condition_allowed == 1) {  // a variable from input
    $exp_ranges = AllowedExpRange::where('category_id', '=', $category_id)->get();

    $user_query = $user_query->where(function($q) use($exp_ranges) {
         foreach($exp_ranges as $range) {
             $q->orWhereBetween("exp_in_months", [$range->starting_exp_months , $range->end_exp_months]);
         }
    }
}

//there are still other conditions to be chained to $user_query after checking the experience range
$user_query = $user_query->get();

The above code upon execution fails with "Column not found: 1054 Unknown column 'exp_in_months' in 'where clause'", because alias cannot be used in where on same level of SQL. How to use an alias from select in the following chained where/whereBetween queries using eloquent?

I'm able to achieve closest output by getting collection output just before exp_range and filtering the collection output with different conditions, but I could not chain the succeeding conditions to $user_query after exp_range condition.

Few posts suggest to use "having" clause when raw sql is executed, but multiple nested having clauses (like orHaving along with 'between' clause) does not seem to be possible. Any suggestion/clue to chain the exp_range conditions to $user_query is welcome.

Thanks in advance!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
    • ¥15 微信会员卡接入微信支付商户号收款
    • ¥15 如何获取烟草零售终端数据
    • ¥15 数学建模招标中位数问题
    • ¥15 phython路径名过长报错 不知道什么问题
    • ¥15 深度学习中模型转换该怎么实现
    • ¥15 HLs设计手写数字识别程序编译通不过
    • ¥15 Stata外部命令安装问题求帮助!
    • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
    • ¥15 TYPCE母转母,插入认方向