Can you share the code you’ve tried so far? It’ll be easier to help you.
Jul 22, 2025
8
Level 2
Latest record many to many relationship
Hi,
I have 3 tables :
-
dossier
- id
-
status
- id
-
dossier_statuses
- dossier_id
- status_id
- created_at
I'd like to retrieve dossier where their last status saved is of a specific status (id).
I tried few things but it doesn't work. I get all dossier with this specific status but for some, this status is not the last.
If anybody can help me
Level 41
The solution can be more straightforward and simpler than we all thought.
Let's ignore the relationships for now, we can write a database query using addSelect with dossier and and dosier_statuses tables only.
Dossier::addSelect(['last_status_id' => DB::table('dossier_statuses')->select('status_id')
->whereColumn('dossier.id', 'dossier_statuses.dossier_id')
->latest('dossier_statuses.id')
->limit(1)
])
->having('last_status_id', $yourSpecificStatusId)
->get();
Pls let me know if this works.
1 like
Please or to participate in this conversation.