我有一个函数返回用户的database notifications(用户模型是Notifiable):
return $user->notifications()->get();
返回的结果如下:
[
{
"id": "5d6548d3-1f9b-4da5-b332-afbf428df775",
"type": "Meysam\\Notification\\Classes\\CommentCreated",
"notifiable_id": 1,
"notifiable_type": "RainLab\\User\\Models\\User",
"data": {
"userId": 2,
"commentId": 18
},
"read_at": null,
"created_at": "2018-03-05 09:58:34",
"updated_at": "2018-03-05 09:58:34"
},
{
"id": "2e22e24e-a972-4a30-afeb-0049a40966a7",
"type": "Meysam\\Notification\\Classes\\CommentCreated",
"notifiable_id": 1,
"notifiable_type": "RainLab\\User\\Models\\User",
"data": {
"userId": 3,
"commentId": 17
},
"read_at": null,
"created_at": "2018-03-05 09:38:38",
"updated_at": "2018-03-05 09:38:38"
}
]
在返回之前修改此集合的最佳方法是什么?例如,我想从对象中删除"id"
字段,将"type"
字段的值更改为"CommentCreated"
,并将"url", "username", "email", etc
等新字段添加到每个项目。将hidden
,visible
和append
attributes添加到DatabaseNotification
模型类(如果是这样,如何)是一个好主意? API Resources在这里有用吗?
适用于Laravel 5.5+
对于Laravel <5.5
正如@linktoahref所建议的那样,最好使用分形。
根据定义,REF:http://fractal.thephpleague.com/
Fractal为复杂的数据输出提供了一个表示和转换层,就像在RESTful API中找到的那样,并且与JSON非常相似。可以将其视为JSON / YAML /等的视图层。
您可以使用分形将数据转换为适当的格式,在使用laravel时,最好为每个模型创建分形并在需要时使用。它可以接受模型并对每个字段执行转换并以适当的数据格式返回。
spatie/laravel-fractal
是开始分形的好方法。
如果您只想更改集合的返回值,那么可以这样做:
$user->notifications()->get()->map(function($item) {
unset($item['id']); //remove id
$item['type'] = "CommentCreated"; //change the value of "type" field
$item['url'] = "url content"; //add new data
$item['username'] = "username content"; //add new data
$item['email'] = "email content"; //add new data
return $item;
});