Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 获取laravel中用户的角色ID数组_Php_Arrays_Laravel - Fatal编程技术网

Php 获取laravel中用户的角色ID数组

Php 获取laravel中用户的角色ID数组,php,arrays,laravel,Php,Arrays,Laravel,这是用户型号: class User extends Model { /** * The roles that belong to the user. */ public function roles() { return $this->belongsToMany('App\Role'); } } 这是角色模型: class Role extends Model { /** * The users th

这是用户型号:

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}
这是角色模型:

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}
正如您所看到的,这两个模型之间存在多对多关系

现在我想获得一个用户角色的ID的数组。为此,我写了这篇文章:

$user = User::find($id);
return $user->roles()->get(['roles.role_id']);
但上面的代码返回一个数组,其中包含引用用户拥有的每个角色ID的对象:

[
    {
        "role_id": 9,
        "pivot": {
            "user_id": 2,
            "role_id": 9
        }
    },
    {
        "role_id": 14,
        "pivot": {
            "user_id": 2,
            "role_id": 14
        }
    }
]
但我想返回一个角色ID数组,如下所示:

[9,14,......]
我如何才能做到这一点?

雄辩的函数有助于做到这一点。请注意,它返回的是一个集合,而不是数组,因此,如果必须使用数组,则还需要
toArray

$roles = $user
  ->roles()
  ->lists('roles.role.id')
  ->toArray();
更新:(对于>=5.2版本)

在laravel版本>=5.2中,lists()方法已被弃用,请改用pull()方法:

$roles = $user
  ->roles
  ->pluck('id')
  ->toArray();
如果您需要字符串,例如在刀片中,您可以在不使用toArray()附件的情况下使用:

$roles = $user
  ->roles
  ->pluck('id');

可以在对象上循环以仅获取
角色\u id