我有一個簡單的 where 查詢,它在 foreach 中重復(fù)了一段時間,實(shí)際上可能很多,所以這是我的查詢: 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]; } }所以每次運(yùn)行它在望遠(yuǎn)鏡中大約需要 2,509.10 毫秒,這是望遠(yuǎn)鏡向我顯示的作為在表上運(yùn)行的查詢的內(nèi)容 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"那么關(guān)于如何優(yōu)化此查詢的任何想法?
1 回答

慕娘9325324
TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個贊
好吧,根據(jù)經(jīng)驗(yàn) - 不要在循環(huán)內(nèi)運(yùn)行查詢。
您可以whereIn()用于查詢多個 ID
$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');
- 1 回答
- 0 關(guān)注
- 125 瀏覽
添加回答
舉報(bào)
0/150
提交
取消