在laravel中使用php从多个关系返回特定列

在laravel中使用php从多个关系返回特定列,php,laravel-4,many-to-many,transform,Php,Laravel 4,Many To Many,Transform,在我的数据库中,我有两个模型,用户和角色定义为多个关系,我试图在laravel中编写一个代码,从角色表中获取id,并从用户表中获取所有用户全名 我定义了一条如下所示的路线: Route::get('roleUser/{role}', 'RoleController@RoleNames'); 在其中,我将角色名与它一起传递,如上面所示 在我的RoleControl中,我定义了roleNames方法来完成这项工作 public function RoleNames($role) { $

在我的数据库中,我有两个模型,用户和角色定义为多个关系,我试图在laravel中编写一个代码,从角色表中获取id,并从用户表中获取所有用户全名

我定义了一条如下所示的路线:

Route::get('roleUser/{role}', 'RoleController@RoleNames');
在其中,我将角色名与它一起传递,如上面所示

在我的RoleControl中,我定义了roleNames方法来完成这项工作

public function RoleNames($role)
{


    $idrole = Role::where('name', '=', $role)->first()->id;
    //$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole)->first()->id;
    $iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole)->get(array('id'));

    $usersUnderRole = array();
    foreach ($iduser as $idusers) {

        $usersUnderRole = array_add($usersUnderRole, $idrole, $idusers);

         $full_name = DB::table('users')->where('id', '=', $idusers)->get()->full_name;
     }
         return $this->respond([
             'result' => $this -> roleTransformer->transform($full_name)

         ]);
}
此代码旨在从roles表中获取role_id,并通过pivot表分配的_roles获取相应的用户_id,将其放入数组中并获取相应的全名,但它显示以下错误:

类stdClass的对象无法转换为字符串
关于如何让它工作有什么建议吗

这将为您提供属于给定角色的所有用户:

$role_id = 3;

$result = DB::table('role_user')
  ->select('users.full_name')
  ->where('role_user.role_id', $role_id)
  ->leftJoin('users', 'users.id', '=', 'role_user.user_id')
  ->get();

var_dump($result);

$full_name=DB::table'users'->其中'id','=',$idusers->列出'users.full_name'

除了@lamzazo提供的解决方案之外,还有另一种方法可以解决这个问题:

        $role2 = Role::where('name', '=', $role)->first();

        $idrole = Role::where('name', '=', $role)->first()->id;
        //$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole);
        $user = DB::table('assigned_roles')->where('role_id', '=', $idrole)->get();
       // $user = DB::table('users')->where('id', '=', $iduser);


        // return $this->respond($iduser[0]->user_id);


       $userArray = array();

        $i=0;

        foreach ($user as $users) {
            $iduser= $users->user_id;
            $allusers = User::where('id', '=', $iduser)->get(array('id', 'full_name'));
            $userArray = array_add($userArray, $i . '', $allusers);
            $i++;

        }



       return $this->respond([
              'result' => $this -> roleTransformer->testTransform($role2, $userArray)

       ]);

$full_name=DB::table'users'->其中的'id','=',$idusers->get->full_name;这部分很奇怪,查询生成器get将返回一个集合,而不是一行。你的意思是…->first->full_name吗?我正在尝试获取与指定角色相关的所有用户名,而不仅仅是第一个用户@lamzoelount没有扮演角色?你坚持使用查询生成器吗?这可以用几句雄辩的台词来完成。非常感谢,这实际上很有帮助@lamzozo