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

时间:2015-08-19 08:02:31

标签: php mysql laravel eloquent relationship

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

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

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

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

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

它应该返回以下输出

 [ 
   {
     "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
        }
     ]
   }
 ]

1 个答案:

答案 0 :(得分:24)

就个人而言,我不会改变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()

相关问题