从相关的laravel模型中获取具有belongsToMany关系的ids数组

sp1*_*p11 18 php mysql relationship laravel eloquent

我有一个模型角色,属于许多用户.

Class Role {
     public $fillable = ["name"];

     public function users()
     {
          return $this->belongsToMany('App/Models/User')->select(['user_id']);
     }
}
Run Code Online (Sandbox Code Playgroud)

当我在Role中检索使用查询的用户时.我希望它只返回user_ids数组

 Role::with("users")->get();
Run Code Online (Sandbox Code Playgroud)

它应该返回以下输出

 [ 
   {
     "name": "Role1",
     "users" : [1,2,3]
   },
   {
     "name": "Role2",
     "users" : [1,2,3]
   }
 ]
Run Code Online (Sandbox Code Playgroud)

目前它提供以下输出

[ 
   {
     "name": "Role1",
     "users" : [
        {
           user_id : 1
        },
        {
           user_id : 2
        },

        {
           user_id : 3
        }
   },
   {
     "name": "Role2",
     "users" : [
        {
           user_id : 1
        },
        {
           user_id : 2
        },

        {
           user_id : 3
        }
     ]
   }
 ]
Run Code Online (Sandbox Code Playgroud)

ben*_*enJ 31

就个人而言,我不会改变users()关系,但可能会为用户ID添加一个访问者

class Role {
    protected $fillable = ["name"];

    // adding the appends value will call the accessor in the JSON response
    protected $appends = ['user_ids'];

    public function users()
    {
         return $this->belongsToMany('App/Models/User');
    }

    public function getUserIdsAttribute()
    {
        return $this->users->pluck('user_id');
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您仍然具有工作关系,但可以在角色响应中将用户ID作为数组进行访问.如果这对你不起作用,正如@Creator所提到的,你可能只是添加->pluck('id')关系而不是select()

  • 在 Laravel 5.5+ 中,我需要执行 `return $this->users->pluck('pivot.user_id');` 或者只是使用“id”。 (4认同)
  • 这很慢 - 您使用 `$this->users->pluck()` 访问它应该是 `$this->users()->pluck('feild')->get()` (3认同)
  • @AndrewMcLagan erm,nope,调用`$ this-> users()`返回查询构建器.调用`$ this-> users`返回急切加载的集合.你可以做`$ this-> users() - > pluck('field')`,但是当你重复查询时,这会慢一些. (3认同)
  • [此处](https://laracasts.com/discuss/channels/general-discussion/eloquent-get-relations-id-belongstomany)这些人使用了`$this->users()->allRelatedIds();`。@benJ,你的建议也适用于此吗? (2认同)