雄辩的-如何在更多情况下使用别名?

时间:2018-12-13 18:42:03

标签: php mysql laravel eloquent alias

继续讨论线程MYSQL How to perform custom month difference between two dates in MYSQL?中的问题,我尝试仅在具有导出的“ exp_in_months”结果以及少数其他条件的条件下加入allowed_exp_range表。下面是详细信息。

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();

上面的代码在执行时失败,并显示“找不到列:1054'where子句中的未知列'exp_in_months'”,因为别名不能在相同级别的SQL上的where中使用。如何通过雄辩地在以下链接的where / whereBetween查询中使用select中的别名?

我能够通过在exp_range之前获取集合输出并使用不同条件过滤集合输出来获得最接近的输出,但是我无法在exp_range条件之后将后续条件链接到$ user_query。

很少有文章建议在执行原始sql时使用“ having”子句,但是似乎无法使用多个嵌套的hading子句(例如orHaving和'between'子句)。欢迎提供任何将exp_range条件链接到$ user_query的建议/线索。

谢谢!

0 个答案:

没有答案