簡體   English   中英

如何在Laravel中向表述模型對象集合添加元字段

[英]How to add a meta field to a collection of Eloquent model objects in Laravel

我有一個通過多對多關系連接的設備模型和讀數模型。 我正在使用一個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
     }

   }
]

任何幫助,將不勝感激。 謝謝

您可以通過以下方式實現:

public function getUserDevices($user_id){

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

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

您應該能夠創建一個關系,將結果限制為最新的關系,像這樣

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

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

在渴望加載它們時限制讀數

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM