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


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

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
        }
     ]
   }
 ]

8830
2017-08-19 08:02


起源

您可以使用它来实现它 ->lists('user_id') 代替 ->all()。 - Jeemusu
试试这个返回$ this-> belongsToMany('App / Models / User') - > lists('user_id'); - Anil Sharma
对不起,我用“ - >得到”不是“ - >全部”。我已经编辑了我的问题。 @Jeemusu,它为所有记录提供了一系列ID,每个角色需要user_ids - sp11
@Creator我试过使用列表但没有工作 - sp11


答案:


就个人而言,我不会改变 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所提到的,你可能只是添加 ->lists('id') 在关系而不是 select()


16
2017-08-19 08:47



它的工作原理。谢谢 :) - sp11
在Laravel 5.5+我需要做 return $this->users->pluck('pivot.user_id'); 或者只是使用“id”。 - llioor
这很慢 - 你正在使用它 $this->users->pluck() 应该 $this->users()->pluck('feild')->get() - AndrewMcLagan
@AndrewMcLagan呃,不,打电话 $this->users() 返回查询构建器。调用 $this->users 返回急切加载的集合。你可以做到 $this->users()->pluck('field'),但是当你重复查询时,这会慢一些。 - benJ