json 如何使用Laravel解析字段名

jbose2ul  于 2023-10-21  发布在  其他
关注(0)|答案(3)|浏览(144)

我的控制器代码:

public function usersGroups(Request $request)
   {
    $resultArray = [];

        $users = DB::table('users')
            ->join('user_basic_info','users.id','=','user_basic_info.user_id')
            ->select('users.id','user_basic_info.first_name')->get();
        $resultArray['users'] = $users;

        $groups = DB::table('group')
            ->select('group.id','group.name')->get();
        $resultArray['groups'] = $groups;

    return \Illuminate\Support\Facades\Response::json($resultArray, 200);
}

我的回答是:

{
"users": [
    {
        "id": 1,
        "first_name": "Admin"
    },
    {
        "id": 2,
        "first_name": "Admin"
    },
    {
        "id": 3,
        "first_name": "Admin"
    },
    {
        "id": 4,
        "first_name": "Admin"
    }
],
"groups": [
    {
        "id": 1,
        "name": "Our Lira"
    },
    {
        "id": 2,
        "name": "CM"
    }
  ]
     }

我有一个字段名“first_name”,我想将其更改为“name”,而不更改表中的字段名。对于这个API,我想将first_name改为name。我如何才能做到这一点?

mv1qrgav

mv1qrgav1#

你可以简单地使用MySQL创建一个别名:

$users = DB::table('users')
            ->join('user_basic_info','users.id','=','user_basic_info.user_id')
            ->select('users.id','user_basic_info.first_name as name')->get();

注意select查询中的as name

cvxl0en2

cvxl0en22#

使用API Resource
这些类允许您将模型转换为您想要的任何JSON格式/布局。

kmynzznz

kmynzznz3#

我不太擅长API,但你可以通过设置alaias名称来实现

public function usersGroups(Request $request)
   {
    $resultArray = [];

        $users = DB::table('users')
            ->join('user_basic_info','users.id','=','user_basic_info.user_id')
            ->select('users.id','user_basic_info.first_name as name')->get();
        $resultArray['users'] = $users;

        $groups = DB::table('group')
            ->select('group.id','group.name')->get();
        $resultArray['groups'] = $groups;

    return \Illuminate\Support\Facades\Response::json($resultArray, 200);
}

如果有任何错误,请在下面评论

相关问题