如何在laravel

时间:2019-07-23 06:27:22

标签: php laravel eloquent relationship

enter image description here enter image description here enter image description here我正在尝试使用带有关联关系的字段名称:

我的代码:

public function getAllUsers()
{
    $users = User::with('userBasicInfo','roles:name')->get();

    return response([
        'status' => true,
        'message' => "All Users",
        'total' => count($users),
        'data' => $users
    ], 200);
}

当我只使用$users = User::with('userBasicInfo','roles)->get();

它准确地返回了我的记录,当我使用$users = User::with('userBasicInfo','roles:name')->get();

它返回我的null array个角色,我也想使用roles: name显示名称,但不返回任何内容。

2 个答案:

答案 0 :(得分:0)

您的选择语法错误。有效为

  

$ users = User :: with('userBasicInfo,roles:name')-> get();

OR

  

$ users = User :: with([['userBasicInfo','roles:name'])-> get();

答案 1 :(得分:0)

您应该尝试以下操作:

public function getAllUsers()
{
    $users = DB::table('users')
              ->select('users.name','roles.name')
              ->join('userBasicInfo', 'users.userbasicinfo_id', '=', 'userBasicInfo.id')
              ->join('roles', 'users.roles_id', '=', 'roles.id')
              ->get();


    return response([
        'status' => true,
        'message' => "All Users",
        'total' => count($users),
        'data' => $users
    ], 200);
}