如何清除/减少模型实例的属性以减小json大小?

时间:2019-07-11 17:49:29

标签: laravel eloquent pusher

我有一个过程,其中更新了一些模型,然后将更新后的对象发送到Pusher,以通过控制板进行实时跟踪,但是该对象具有其他几个对象作为关系,因此序列化对象的大小超出了pusher限制消息的大小,所以我的问题是如何删除相关对象的某些属性?

我已经尝试过pluck函数,但是我不知道如何在neastead对象上使用

$vehicleEntry = VehicleEntry::with('vehicle')->find($request->entryId);
// I need just the id and plate of the object
$vehicleEntry->pluck('vehicle.id', 'vehicle.plate');

但出现错误

{id:1,车辆:{id:2,板块:'JIS575'},created_at:'2019-07-11'}

2 个答案:

答案 0 :(得分:1)

我个人更喜欢的一种方法是使用API resources。这样,您始终可以完全控制要返回的数据。

示例:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class VehicleEntryResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => (int) $this->resource->id,
            // Watch out with this. Make sure the vehicle relation is loaded.
            // Otherwise it will always add this execute another query for
            // every vehicle entry you send to this class, would be bad when
            // you want to send multiple. You could also use
            // $this->whenLoaded('vehicle'), however this needs another
            // resource.
            'vehicle' => [
                'id' => (int) $this->resource->vehicle->id,
                'plate' => $this->resource->vehicle->plate,
            ],
            'created_at' => $this->resource->created_at,
        ];
    }
}

现在您可以在任何需要的地方打电话给它

new VehicleEntryResource($vehicleEntry);

不确定Pusher消息是否像您通常在控制器中返回的JsonResponse一样好用。在响应中返回时,它将自动将它们转换为数组。但是您也可以执行以下操作来获取数组表示形式:

(new VehicleEntryResource($vehicleEntry))->toArray(null);

答案 1 :(得分:1)

一种简单的方法是在模型中添加一个$hidden属性,并为其提供一个字符串数组,这些字符串是要从json输出中隐藏的属性名称:

protected $hidden = [
    'hide', 
    'these', 
    'attributes', 
    'from', 
    'json'
];

将对象转换为json时,它将自动阻止显示$hidden数组中列出的任何属性。

在此处查看文档:{​​{3}}