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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32089782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:47:21  来源:igfitidea点击:

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

phpmysqllaraveleloquentrelationship

提问by sp11

I have a model Role which belongs to many Users.

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

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

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

When I retrieve users using with query in Role. I want It would return only user_ids array

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

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

it should return the following output

它应该返回以下输出

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

Currently it gives following output

目前它提供以下输出

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

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

        {
           user_id : 3
        }
     ]
   }
 ]

回答by benJ

Personally, I wouldn't change the users()relationship, but maybe add an accessor for user IDs

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

Then you still have a working relationship, but can access the user IDs as an array in the Role response. If that doesn't work for you, as mentioned by @Creator, you could probably just add ->pluck('id')in the relationship rather than the select()

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