我有一个简单的 where 查询,它在 foreach 中重复几次,实际上可能会很多次,所以这是我的查询:
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];
}
}
因此,每次运行时,望远镜都会花费大约 2,509.10 毫秒,这是望远镜向我显示的表上运行的查询
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"
那么关于如何优化这个查询有什么想法吗?
最佳答案
嗯,根据经验 - 不要在循环内运行查询。
您可以使用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');
关于php - laravel 如何优化一个表中的简单 where 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56313509/