首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何清理/缩减模型实例的属性以减小json大小?

如何清理/缩减模型实例的属性以减小json大小?
EN

Stack Overflow用户
提问于 2019-07-12 01:49:30
回答 2查看 310关注 0票数 1

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

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

代码语言:javascript
复制
$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'}

EN

回答 2

Stack Overflow用户

发布于 2019-07-12 02:06:13

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

示例:

代码语言:javascript
复制
<?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,
        ];
    }
}

现在你可以在任何你想调用的地方调用它:

代码语言:javascript
复制
new VehicleEntryResource($vehicleEntry);

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

代码语言:javascript
复制
(new VehicleEntryResource($vehicleEntry))->toArray(null);
票数 3
EN

Stack Overflow用户

发布于 2019-07-12 03:12:24

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

代码语言:javascript
复制
protected $hidden = [
    'hide', 
    'these', 
    'attributes', 
    'from', 
    'json'
];

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

请参阅此处的文档:https://laravel.com/docs/5.8/eloquent-serialization#hiding-attributes-from-json

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56994826

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档