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

Get ids array from related laravel model which is having belongsToMany relationship

我有一个属于许多用户的模型角色。

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

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

当我在 Role 中使用 with query 检索用户时。我想要 return 只有 user_ids 数组

 Role::with("users")->get();

它应该return下面的输出

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

目前它给出以下输出

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

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

        {
           user_id : 3
        }
     ]
   }
 ]

就我个人而言,我不会更改 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');
    }
}

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