I found two solutions:
$query = DB::table('tmteher_monthly_stats as tms')
->select('tms.user_id')
->addSelect('tms.dayoff')
->whereDate('tms.stat_date', '=', $period.'-01')
->where('tms.id', '=', function($query) {
$query->from('tmteher_monthly_stats AS tms2')
->selectRaw('max(tms2.id)')
->whereRaw('tms2.user_id = tms.user_id')
->whereRaw('tms2.stat_date = tms.stat_date');
});
$query = DB::table('tmteher_monthly_stats as tms')
->select('tms.user_id')
->addSelect('tms.dayoff')
->whereDate('tms.stat_date', '=', $period.'-01')
->where('tms.id', '=', function($query) {
$query->select(DB::raw('max(tms2.id)'))
->from('tmteher_monthly_stats AS tms2')
->where('tms2.user_id', '=', DB::raw('tms.user_id'))
->where('tms2.stat_date', '=', DB::raw('tms.stat_date'));
});
Explanation:
The where expression doesn't use properly the apostrophes.
The inner select's where without DB::raw() recognize the field as string. So it's wrong: $query->where(`tms2`.`user_id` = 'tms.user_id')
This code helped me:
DB::enableQueryLog();
$query_success->get();
$query_empty->get();
dd(DB::getQueryLog());
Result:
array:2 [
0 => array:3 [
"query" => "select `tms`.`user_id`, `tms`.`dayoff` from `tmteher_monthly_stats` as `tms` where date(`tms`.`stat_date`) = ? and `tms`.`id` = (select max(tms2.id) from `tmteher_monthly_stats` as `tms2` where `tms2`.`user_id` = tms.user_id and `tms2`.`stat_date` = tms.stat_date)"
"bindings" => array:1 [
0 => "2019-02-01"
]
"time" => 11.65
]
1 => array:3 [
"query" => "select `tms`.`user_id`, `tms`.`dayoff` from `tmteher_monthly_stats` as `tms` where date(`tms`.`stat_date`) = ? and `tms`.`id` = (select max(tms2.id) from `tmteher_monthly_stats` as `tms2` where `tms2`.`user_id` = ? and `tms2`.`stat_date` = ?)"
"bindings" => array:3 [
0 => "2019-02-01"
1 => "tms.user_id"
2 => "tms.stat_date"
]
"time" => 0.71
]
]