Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mrkarma4ya's avatar

Need help with a difficult query

I have an app with Users and Jobs. Each User can have many Jobs. Each Job has a start_date and an end_date.

I want to create a filter that gets a list of users who have a min of X years of experience and a max of Y years of experience.

Years of Experience is typically calculated by getting the difference of start_date and end_date of each job of a user, however, there's a catch. If two jobs have overlapping dates, they should be calculated accordingly.

I created an attribute called work_experience that calculates the value of work experience based on the calculation above and appended it to the User model. So when I call /api/users, I have a 'work_experience' key with the correct value. All good until now.

But when filtering the users, I can't use the work_experience in query builder, since its calculated after the model has been retrieved. I would have to get list of all users with other filters, then filter the collection with required work_experience, which doesn't seem very optimized.

Is there a way to do it at query builder itself, without using the model attributes? Or should I just filter the collection even though it may be slower. I really suck at building queries, so I would like some help.

0 likes
2 replies
SilenceBringer's avatar
Level 55

@mrkarma4ya sometimes it make a common sence to store calculated field in the database. If your case you can add one more field work_experience to users table, and recalculate it every time new job added/finished (according to your logic)

This way you always will have access to the work_experience and can use it as you need (filter, for example).

1 like
teos_97's avatar

@mrkarma4ya another idea you can tinker with is to create a scope and use RAW query to calculate the differences as X field. You can see examples here - https://laravel.com/docs/8.x/queries#raw-expressions As for the calculate date differences - depending on what db you use there might be functions you can make use for. e.g- DATEDIFF(year,'date1','date2') .. etc

Please or to participate in this conversation.