0

i have a simple where query that repeats in a foreach for some times that can be a lot really so here is my query :

    for ($i = 0; $i < count($hasdate); $i++) {
        $roomprice = RoomPricingHistory::
             Where('accommodation_room_id', $hasroom[$i])
            ->where('from_date', '<=', $hasdate[$i])
            ->where('to_date', '>=', $hasdate[$i])
            ->get()->sortBy('created_at');

        $lastget = last($roomprice);
        $last_price = last($lastget);
        if ($last_price) {
            $final_price[] = $last_price->sales_price;
        } else {
            $has_not_capacity = $hasdate[$i];
        }
    }

so each time this runs it takes a bout 2,509.10ms in telescope and here is what the telescope shows me as the query which is running on table

  select
  *
from
  `room_pricing_histories`

    where
      `accommodation_room_id` = 3
      and `from_date` <= "2019-06-01 09:00:00"
      and `to_date` >= "2019-06-01 09:00:00"

so any idea on how to optimize this query ??

2

1 Answer 1

1

Well, as a rule of thumb - don't run a query inside a loop.

You can use whereIn() for the querying multiple IDs

$roomIds = $hasroom // assume this has array of ids

$roomprice = RoomPricingHistory::
        whereIn('accommodation_room_id', $roomIds)
        ->where('from_date', '<=', $fromDate)
        ->where('to_date', '>=', $toDate)
        ->get()->sortBy('created_at');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.