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!