Lumen PHP 更改 JSON 中的字段名称

问题描述 投票:0回答:1

我的数据库中有一个表,其中包含一些字段:

  • id
  • 名字
  • xx

当我调用 API 时,我从数据库中获取一项并将其返回:

$table = MyTable::select('table.*')->where('id', $id)->first();
return response()->json($table, 200);

我得到这样的json:

{
  "id": 1,
  "name": "user1",
  "xx": 0
}

我可以通过将

xx
字段添加到模型内的
$hidden
字段来删除它。

如何重命名

xx
中的
yy
? 是否存在比在模型内的 yy 字段上添加 getter/setter 更简单的方法?

获得:

{
  "id": 1,
  "name": "user1",
  "yy": 0
}
php json lumen
1个回答
0
投票

第一种方法是使用

setHidden
select alias
如下所示:

$table = MyTable::select('table.*', "table.xx as yy")->where('id', $id)->first()->setHidden(["xx"]);
return response()->json($table, 200);

或者您可以使用关联数组映射响应,但您必须映射每个字段,如下所示:

$table = MyTable::select('table.*')->where('id', $id)->first();
return response()->json([
  "id" => $table->id,
  "name" => $table->name,
  "yy" => $table->xx
], 200);

或者像下面这样取消设置:

$table = MyTable::select('table.*')->where('id', $id)->first()->toArray();
$table["xx"] = $table["yy"];
unset($table["yy"]);
return response()->json($table, 200);
© www.soinside.com 2019 - 2024. All rights reserved.