【问题标题】:How to add a meta field to a collection of Eloquent model objects in Laravel如何在 Laravel 中将元字段添加到 Eloquent 模型对象的集合中
【发布时间】:2018-05-26 08:04:35
【问题描述】:

我有一个设备模型和一个读数模型,它们通过多对多关系连接。我正在开发一个 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
     }

   }
]

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

【问题讨论】:

    标签: php json laravel laravel-5 eloquent


    【解决方案1】:

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

    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();
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      public function getUserDevices($user_id){
      
      $devices = Device::with('reading')->where('user_id',$user_id)->get();
      
      return response()->json($devices);
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-15
        • 2018-09-13
        • 2016-12-22
        • 2016-05-17
        • 2015-05-16
        • 2016-02-23
        • 1970-01-01
        • 2013-05-06
        • 2015-02-28
        相关资源
        最近更新 更多