我在laravel中有一个对象数组,我想在这些对象上使用where查询,所以这是下面的代码:
array:18 [▼
0 => RoomPricingHistory {#498 ▼
#fillable: array:19 [▶]
#connection: "mysql"
#table: "room_pricing_histories"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:22 [▶]
#original: array:22 [▼
"id" => 326
"accommodation_room_id" => 1
"net_price" => null
"sales_price" => 3660000
"extra_bed_price" => null
"half_charge_price" => null
"half_board_price" => null
"full_board_price" => null
"foreign_net_price" => null
"foreign_sales_price" => null
"foreign_extra_bed_price" => null
"foreign_half_charge_price" => null
"foreign_half_board_price" => null
"foreign_full_board_price" => null
"operator_id" => 11
"commission_percent" => null
"discount_percent" => 5.0
"from_date" => "2019-05-25 09:00:00"
"to_date" => "2019-08-30 09:00:00"
"is_deleted" => 0
"created_at" => "2019-05-25 09:00:00"
"updated_at" => "2019-05-25 09:00:00"
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
1 => RoomPricingHistory {#506 ▶}
2 => RoomPricingHistory {#513 ▶}
3 => RoomPricingHistory {#520 ▶}
4 => RoomPricingHistory {#527 ▶}
5 => RoomPricingHistory {#534 ▶}
6 => RoomPricingHistory {#541 ▶}
7 => RoomPricingHistory {#548 ▶}
8 => RoomPricingHistory {#555 ▶}
9 => RoomPricingHistory {#562 ▶}
10 => RoomPricingHistory {#569 ▶}
11 => RoomPricingHistory {#576 ▶}
12 => RoomPricingHistory {#583 ▶}
13 => RoomPricingHistory {#590 ▶}
14 => RoomPricingHistory {#597 ▶}
15 => RoomPricingHistory {#604 ▶}
16 => RoomPricingHistory {#611 ▶}
17 => RoomPricingHistory {#618 ▶}
]
所以现在在这里,例如,我在这里有17个房间,其中5个房间有1个,ID为2的5个,ID为3的7个,在这个结果中,我想获取每个房间的最后sales_price,所以我最终房间ID为1 -2 -3且最后的价格为3。只是说我按结果之前的日期对它们进行了排序
答案 0 :(得分:1)
假设您将数据包含在名为$collection
的变量中,然后可以执行以下代码来过滤数据:
我们首先按id
对数据进行分组,然后选择最后一条记录。
$grouped = $collection->groupBy('id')->last();
$grouped->toArray();
答案 1 :(得分:1)
您可以使用以下代码获取最新记录:
for ($f = 0; $f < count($room_id); $f++) {
for ($i = 0; $i < count($dates); $i++) {
$roomprice[$f] = RoomPricingHistory::
Where('accommodation_room_id', $room_id[$f])
->whereDate('from_date', '<=', $dates[$i])
->whereDate('to_date', '>=', $dates[$i])
->orderBy('created_at', 'desc')->first();
}
}