dongliang1865
2019-05-15 08:20
浏览 667
已采纳

如何使用laravel将两个对象合并为一个对象

I am getting objects response like this:

                       "facilities": [
            [
                {
                    "facility_id": 1,
                    "speciality_id": null,
                    "is_facility_supervisor": 0,
                    "priv_key": "can_add_doctor,can_view_doctor"
                }
            ],
            {
                "name": "Patient",
                "role_id": 7
            }
        ]

I want name and role_id into facilities and i want expected output like this

               "facilities": [
            [
                {
                    "facility_id": 1,
                    "speciality_id": null,
                    "is_facility_supervisor": 0,
                    "priv_key": "can_add_doctor,can_view_doctor",
                    "name": "Patient",
                     "role_id": 7

                }
            ],

        ]

How i can achieve this output name and role_id is in separate object but i want in one object like i shared.

My Code:

$specialities = DB::table('user_facility')
->select('user_facility.facility_id','user_facility.speciality_id','user_facility.is_facility_supervisor','user_facility.priv_key')
->where('user_id',$currentUser->id)->get();

         $roles = DB::table('roles')
        ->join('user_facility', 'roles.id', 'user_facility.role_id')
        ->where('user_facility.user_id', Auth::user()->id)
        ->select('roles.name','user_facility.role_id')->first();

    $superadmin = $is_super_admin->is_super_admin;
    $specialities = (object) $speciality_id;

    $response = ['is_super_admin' => $superadmin, 'facilities' => array_merge([$specialities,$roles])];

Your help will be highly appreciated?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • doumicheng6732 2019-05-15 08:29
    最佳回答

    How about:

    $specialitiesAndRoles = DB::table('roles')
    ->join('user_facility', 'roles.id', 'user_facility.role_id')
    ->where('user_facility.user_id', Auth::user()->id)
    ->select('user_facility.facility_id','user_facility.speciality_id','user_facility.is_facility_supervisor','user_facility.priv_key','roles.name','user_facility.role_id')
    ->get();
    

    When you are anyway joining both tables. Just select everything from the joined table. Please check/add if you have any more where clauses.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题