给定以下表结构,我想返回一个Eloquent集合,或者至少将原始DB结果转换为关联数组以便于迭代。
建筑物
+----+---------------+
| id | building_name |
+----+---------------+
| 1 | Building 1 |
| 2 | Building 2 |
+----+---------------+
房间
+----+-----------+-------------+
| id | room_name | building_id |
+----+-----------+-------------+
| 1 | Room 1 | 1 |
| 2 | Room 2 | 1 |
| 3 | Room 3 | 2 |
+----+-----------+-------------+
maintenancelog
+----+-------------------+---------+---------------------+
| id | maintenance_value | room_id | created_at |
+----+-------------------+---------+---------------------+
| 1 | Cleaned | 1 | 2015-09-10 00:54:59 |
| 2 | Cleaned | 1 | 2015-09-13 01:55:59 |
| 3 | Cleaned | 2 | 2015-09-09 02:56:59 |
| 4 | Cleaned | 2 | 2015-09-14 03:57:59 |
| 5 | Cleaned | 3 | 2015-09-08 04:58:59 |
| 6 | Cleaned | 3 | 2015-09-15 05:59:59 |
+----+-------------------+---------+---------------------+
现在使用以下原始数据库查询..
$results = DB::select('
select b.building_name,r.room_name,x.maxdate FROM buildings b
join rooms r on r.building_id = b.id
join (select room_id,max(created_at) as maxdate from maintenancelog group by room_id) x on x.room_id=room.id
having x.maxdate < DATE_SUB(NOW(), INTERVAL 10 DAY)');
返回
Array
(
[0] => stdClass Object
(
[building_name] => Building 1
[room_name] => Room 1
[maxdate] => 2015-09-13 01:55:59
)
[1] => stdClass Object
(
[building_name] => Building 1
[room_name] => Room 2
[maxdate] => 2015-09-14 03:57:59
)
[2] => stdClass Object
(
[building_name] => Building 2
[room_name] => Room 3
[maxdate] => 2015-09-15 05:59:59
)
是否有给定数组的Laravel辅助函数,我可以指定键和分组命令吗?有点像,按building_name,room_name分组,这样它将返回一个带有&#34; buildings&#34;的集合或关联数组。和&#34;房间&#34;作为使迭代更容易的关键?我可以建立一个,但这似乎是一个常见的任务。 (我做了搜索)
我使用Eloquent并为表格制作模型,但查询对我来说太复杂了,无法弄清楚如何将其变成Eloquent语句。那么即使有一种方法可以使用现有模型创建集合吗?
(注意我已经弄清楚如何使用关系和查询范围从维护日志 - >房间 - >建筑物向后工作。但它将建筑物置于关系的最低层,我希望它是第一个)
答案 0 :(得分:0)
:
public function rooms(){
return $this->hasMany('App\Room');
}
在Room class:
public function maintenanceLog(){
return $this->hasMany('App\MaintenanceLog');
}
public function scopeLongest($query){ //you can name it as you like ofc.
return $query->orderBy('created_at','desc')->first();
}
最后你可以使用:
foreach(Building::all() as $building){
foreach($building->rooms() as $room){
echo 'building: ' . $building->building_name . ' room: ' . $room->room_name . ' maxdate: ' . $room->maintenanceLog()->longest()->created_at;
}
}
答案 1 :(得分:0)
Laravel提供了一些可用于获取所需数组https://laravel.com/docs/5.1/collections#method-put https://laravel.com/docs/5.1/collections#introduction的收集方法。
为了从$ results中获取关联数组,例如
array:3 [
"Building 1" => "Room 1"
"Building 1" => "Room 2"
"Building 1" => "Room 3"
]
要解决您的问题,请创建一个集合对象
$collection_obj = collect();
循环$ results
foreach ($results as $result) {
$collection_obj->put($result->building_name, $result->room_name);
}
然后要将您的集合转换为数组,请使用toArray()
$result_arr = $collection_obj->toArray();
我希望这可以解决您的问题或至少为了参考。