I have a system in which many items can be approved and the history of approvals can be seen on each item. An example is a user's milestone, which can be approved or rejected. The tables in my database book like this:
+-----------------+------------------+
| Approvals |
+-----------------+------------------+
| Field | Type |
+-----------------+------------------+
| id | int(10) unsigned |
| approved | tinyint(1) |
| reason | text |
| approvable_id | varchar(191) |
| approvable_type | varchar(191) |
| created_at | timestamp |
| updated_at | timestamp |
+-----------------+------------------+
+----------------------+---------------------------------------+
| Milestones |
+----------------------+---------------------------------------+
| Field | Type |
+----------------------+---------------------------------------+
| id | int(10) unsigned |
| name | varchar(191) |
| created_at | timestamp |
| updated_at | timestamp |
+----------------------+---------------------------------------+
What I want to be able to do is fetch all milestones where the last approval is accepted. For example a milestone may have been previously accepted, but later reject, in which case this milestone should not appear in the accepted query, as it has since been rejected.
How can I only fetch milestones in which the latest approval is accepted? The approach I have tried so far is to make an exist sub query which checks if milestones has an approval, that is accepted. However, this also fetches results which have been accepted and later rejected:
SELECT * FROM `milestones`
WHERE EXISTS (
SELECT * FROM `approvals`
WHERE `milestones`.`id` = `approvals`.`approvable_id`
AND `approvals`.`approvable_type` = 'App\Models\Milestone'
AND `created_at` = (
SELECT MAX(created_at) FROM `approvals` AS `sub`
WHERE sub.approvable_id = approvals.approvable_id
AND sub.`approvable_type` = `approvals`.`approvable_type`
AND `sub`.`id` IN (
SELECT `id` FROM `approvals`
WHERE `approved` = 1
)
)
) AND `milestones`.`deleted_at` IS NULL
Is it possible to grab all milestones where the latest approval is accepted? Or would this have to be done on the application level instead?

