如何在模型中为列名添加别名?我想在API响应中显示idUser
而不是id。到目前为止,我已经尝试了以下方法。
protected $maps = [
'id' => 'idUser',
];
protected $visible = [
'idUser'
];
protected $appends = [
'idUser'
];
这给了我一个错误:
“调用未定义的方法App \ User :: getIdUserAttribute()”
此外,我想将created_at和updated_at别名为createdAt和updatedAt。
答案 0 :(得分:1)
您可以像这样在模型中定义访问器方法:
public function getUserIdAttribute($)
{
return $this->id;
}
然后必须在$appends
数组中添加属性名称
protected $appends = ['user_id'];
有关更多详细信息,请查看docs
答案 1 :(得分:0)
正如@Namoshek的评论一样,您应该能够通过重命名为每一列返回自定义别名。
首先,在文件夹routes/api.php
中查找要编辑的路由。您可以使用回调函数或控制器来管理响应。
// routes/api.php
Route::middleware('auth:api')->get('auth/retrieve-user', function(Request $request) {
$user = Auth::user();
return response()
->json([
'userId' => $user->id,
'createdAt' => $user->created_at,
'updatedAt' => $user->updated_at,
]);
});