如何在Laravel

时间:2018-05-26 08:04:36

标签: php json laravel laravel-5 eloquent

我有一个Device模型和一个Readings模型,它们通过多对多关系连接起来。我正在开发一个API,它将所有已注册设备的数组返回给特定用户。我想要的是响应中的一个字段,它显示了读数表中的最后一个条目。

这是返回响应的方法。

public function getUserDevices($user_id){

    $devices = Device::where('user_id',$user_id)->get();
    return response()->json($devices);
}

我目前得到的回复。

[
   {
     "id": 2,
     "user_id": 1,
     "device_name": "My Device",
     "device_type": "Sensor",
     "status": 1,
     "created_at": "2018-05-01 14:39:35",
     "updated_at": "2018-05-13 17:56:56",
     "device_key": "60:01:94:37:D1:34",
     "actuator": 0,
     "mode": 1
   },
   {
     "id": 3,
     "user_id": 1,
     "device_name": "Home Device",
     "device_type": "Sensor",
     "status": 1,
     "created_at": "2018-05-01 14:40:25",
     "updated_at": "2018-05-12 13:42:00",
     "device_key": "60:01:94:37:D1:35",
     "actuator": 0,
     "mode": 0
   }
]

我想要的回复。

[
   {
     "id": 2,
     "user_id": 1,
     "device_name": "My Device",
     "device_type": "Sensor",
     "status": 1,
     "created_at": "2018-05-01 14:39:35",
     "updated_at": "2018-05-13 17:56:56",
     "device_key": "60:01:94:37:D1:34",
     "actuator": 0,
     "mode": 1

     "reading":{    <--- This is what i want in every item of the collection
         "temp": 45,
         "hum" : 60
     }

   },
   {
     "id": 3,
     "user_id": 1,
     "device_name": "Home Device",
     "device_type": "Sensor",
     "status": 1,
     "created_at": "2018-05-01 14:40:25",
     "updated_at": "2018-05-12 13:42:00",
     "device_key": "60:01:94:37:D1:35",
     "actuator": 0,
     "mode": 0

     "reading":{    <--- This is what i want in every item of the collection
         "temp": 35,
         "hum" : 76
     }

   }
]

任何帮助将不胜感激。感谢名单

2 个答案:

答案 0 :(得分:0)

您可以通过以下方式执行此操作:

public function getUserDevices($user_id){

$devices = Device::with('reading')->where('user_id',$user_id)->get();

return response()->json($devices);
}

答案 1 :(得分:0)

您应该能够创建一个关系,将结果限制为最新的关系,例如

public function latestReading()
{
    return $this->belongsToMany('Reading')
                ->orderBy('created_at', 'DESC')
                ->limit(1)
                ->first();
}

$devices = Device::with('latestReading')->where('user_id',$user_id)->get();

limit readings when eager loading them

$devices = Device::with(['readings' => function($query) {

              $query->orderBy('created_at', 'DESC')->limit(1)->first();

           }])->where('user_id',$user_id)->get();