繁体   English   中英

从相关的laravel模型中获取具有belongsToMany关系的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中检索使用查询的用户时。 我希望它只返回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
        }
     ]
   }
 ]

就个人而言,我不会更改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') pluck ->pluck('id')而不是select()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM