我有一个过程,其中一些模型被更新,之后我通过控制板将更新后的对象发送到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'}
发布于 2019-07-12 02:06:13
我个人更喜欢的一种方式是使用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);
我不确定推送消息是否像你通常在控制器中返回的JsonResponse
一样好用。当在响应中返回它时,它会自动将它们转换为数组。但您也可以执行以下操作来获取数组表示:
(new VehicleEntryResource($vehicleEntry))->toArray(null);
发布于 2019-07-12 03:12:24
一种简单的方法是向您的模型添加一个$hidden
属性,并为其提供一个字符串数组,这些字符串数组是您希望在json输出中隐藏的属性名称:
protected $hidden = [
'hide',
'these',
'attributes',
'from',
'json'
];
当您的对象被转换为json时,它将自动阻止$hidden
数组中列出的任何属性出现。
请参阅此处的文档:https://laravel.com/docs/5.8/eloquent-serialization#hiding-attributes-from-json
https://stackoverflow.com/questions/56994826
复制相似问题