gpt4 book ai didi

Laravel:删除返回结果中的属性

转载 作者:行者123 更新时间:2023-12-03 15:19:45 25 4
gpt4 key购买 nike

我有以下代码:

$orders = Order::all();
return $orders;

这将返回如下内容:
[
{
"id": 123,
"qr_code": "foo.png",
"qr_code_url": "http://example.com/foo.png"
},
{
"id": 112,
"qr_code": "bar.png",
"qr_code_url": "http://example.com/var.png"
}
]

请注意 qr_code_url是附加属性,而不是存储在数据库中的属性。

我想将此集合返回给没有属性的用户: qr_code , 在这种情况下。所以像这样:
[
{
"id": 123,
"qr_code_url": "http://example.com/foo.png"
},
{
"id": 112,
"qr_code_url": "http://example.com/var.png"
}
]

查看集合函数,我似乎找不到一种简单的方法来做到这一点:
https://laravel.com/docs/5.4/collections

我发现的唯一接近我想要的功能是: exceptforget ,但它们似乎只适用于一维数组。不是模型返回的集合结果。

我该如何解决我的问题?

最佳答案

您可以在模型类中将您的属性设置为隐藏(请参阅 Hidding Attributes From Json )

/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = ['qr_code'];

该属性仍将被加载,但不会显示在您的集合中。

如果你不想让它永久化,你可以使用 makeHidden()文档中描述的 eloquent 方法:

Temporarily Modifying Attribute Visibility

If you would like to make some typically hidden attributes visible on a given model instance, you may use the makeVisible method. The makeVisible method returns the model instance for convenient method chaining:

return $user->makeVisible('attribute')->toArray(); 

Likewise, if you would like to make some typically visible attributes hidden on a given model instance, you may use the makeHidden method.

return $user->makeHidden('attribute')->toArray();

关于Laravel:删除返回结果中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45777058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com