I am trying to apply a different set of date filter depending on the values of the start_date and end_date column of the robot table
Condition
- If robot start date && robot end date are both null => return all data back
- Else if the robot's start date is NULL and the end date is not NULL, return all data where the created_at date of computer_vision_detections is less than or equal to the robot's end_date (only comparing the date, ignoring the time).
Issue
There is an issue with how the WHEN portion of the query is applied such that despite both the start_date and end_date column being NULL it is still entering the second WHEN query causing no data to be returned when there is supposed to be 500 data entries returned
Code
$robot = App\Robot::with([
'computer_vision_detections' => function ($query) {
$query->leftJoin('cv_detection_object_values', function ($join) {
$join->on('computer_vision_detections.detection_object_id', '=', 'cv_detection_object_values.id')
->whereColumn('computer_vision_detections.detection_type_id', '=', 'cv_detection_object_values.detection_type_id');
})
->leftJoin('robots', 'computer_vision_detections.serial_number', '=', 'robots.serial_number')
->select(
'computer_vision_detections.*',
'cv_detection_object_values.detection_type_id AS cv_detection_object_values_detection_type_id',
'cv_detection_object_values.id AS cv_detection_object_values_id_detection_object_id',
'cv_detection_object_values.description AS cv_detection_object_values_description'
)
->where(function ($query) {
$query->when(
DB::raw('robots.start_date IS NULL AND robots.end_date IS NULL'),
function ($q) {
$q->whereNotNull('computer_vision_detections.id'); // Take all data if both start and end are null
}
)
->when(
DB::raw('robots.start_date IS NULL AND robots.end_date IS NOT NULL'),
function ($q) {
$q->whereRaw('DATE(computer_vision_detections.created_at) <= DATE(robots.end_date)'); // All data before or equals to end date
}
);
});
},
'computer_vision_detections.detection_type' // This assumes the relationship is defined properly
])
->find(9434);
Debugging
When the WHEN query is just reduced to this one condition, it is able to return the 500 data entries which indicates to me that there is no issue with this portion of the query and that the issue is due to the second WHEN query also being executed despite the end_time being NULL hence resulting in the entries returned being 0
->where(function ($query) {
$query->when(
DB::raw('robots.start_date IS NULL AND robots.end_date IS NULL'),
function ($q) {
$q->whereNotNull('computer_vision_detections.id'); // Take all data if both start and end are null
}
);
});