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

movepixels's avatar

Complicated Query Help

I will try to explain in detail as this is quite difficult. A User can belong to many Area so I have a pivot for that area_user pivot I have a pivot of user_upgrade (user_id, upgrade_id, area_id, expires) An upgrade has a set duration, keep it simple say 7 days hence the expires in the user_upgrade pivot table. And each area is only allowed a specific number of "upgrades" per week.

What I need is in English get all available upgrade (upgrade_id) for the next 10 weeks that have not gone over the allowed upgrades for that area.

This gets me 1 specific count for an upgrade:

// GET THE NUMBER OF UPGRADES CURRENTLY USED
    $used = DB::table('profile_upgrade')->where('upgrade_id', 1)->where('area_id', $area_id)->whereDate('end_date', $expiration)->count();

But if user has 5 areas, and there are 4 possible upgrades for the next 4 weeks looping thru this will be 5 queries * 4 possible upgrades * 10 weeks is a hell of a lot of queries.

And ultimately I only want maximum of 4 results returning the first available upgrade within the next 10 weeks. So if all spots for area 10 in week 1 for upgrade 1 are filled exclude it and move onto week 2, if available stop since we only need 1 record per upgrade, move onto finding what available for upgrade 2.

Idealy the query result would be like:

0 => [
    upgrade_id => 1,
    week => 2,
    area_id => 25
],
1 => [
    upgrade_id => 2,
    week => 4,
    area_id => 17
],
2 => [
    upgrade_id => 3,
    week => 1,
    area_id => 2
],
3 => [
    upgrade_id => 4,
    week => 6,
    area_id => 11
],

I know this is quite an ask but any insight / ideas / suggestions would be much appreciated.

The easiest way to think about it in real world scenario would be the Staple Center has an event of x number of days and there a limited number of seats per upgrade (vip, back stage, general admission, floor) so I would like to display the first available upgrade available per upgrade for any of those days but once an upgrade is found for each upgrade (vip, back stage, general admission, floor) stop looking.

Dave

0 likes
0 replies

Please or to participate in this conversation.