To conditionally show the end_date only if all campaigns with a specific message_id have an end_date that is not null, you can use a combination of SQL functions and conditional logic. Specifically, you can use a CASE statement to check if there are any campaigns with a null end_date for each message_id. If there are none, you can display the minimum end_date.
Here's how you can modify your query to achieve this:
$resultsData = DB::table('results as lg')
->leftJoin('campaigns as cp', 'campaign_id', '=', 'cp.id')
->leftJoin('messages as msg', 'message_id', '=', 'msg.id')
->selectRaw('
CASE
WHEN COUNT(cp.end_date) = COUNT(*) THEN DATE_FORMAT(MIN(cp.end_date), "%b %d")
ELSE NULL
END as msg_end
')
->selectRaw('SUM(lg.replied) as sumReplied')
->groupBy('message_id')
->get();
Explanation:
-
COUNT(cp.end_date) = COUNT(*): This checks if the count of non-null
end_datevalues is equal to the total count of rows for eachmessage_id. If they are equal, it means there are no nullend_datevalues for thatmessage_id. -
DATE_FORMAT(MIN(cp.end_date), "%b %d"): This formats the minimum
end_datefor themessage_idif allend_datevalues are non-null. -
ELSE NULL: If there are any null
end_datevalues, it returnsNULLformsg_end.
This query will ensure that msg_end is only populated when all campaigns for a given message_id have an end_date.