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']);
     }
}

在角色中使用WITH QUERY检索用户时.我希望它只返回user_ids数组

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

它应该返回以下输出

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

推荐答案

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

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()

Laravel相关问答推荐

Livewire 3软件包开发

Laravel复选框值更新

如何从laravel中的另一个表中获取用户名

Laravel 9:AWS S3 检索要流式传输的视频

Eloquent: hasNot 带参数

如何在 NetBeans 中添加带有点 (blade.php) 的自定义文件扩展名?

Laravel:`loadMissing` 函数的目的是什么?

在 laravel 中更改时区

Laravel 查询构建器 - 如何按别名分组,或进行原始 groupBy

升级到 laravel 5.4 后调用未定义的方法

使用 vue-router 更改路由时中止所有 Axios 请求

如何在包中安排 Artisan 命令?

扩展模型 == 扩展 Eloquent?

命令未定义异常

反向代理后面的 Laravel 路由

Laravel - 动态创建表(无需迁移)

Grammar::parameterize() 必须是数组类型

Eloquent的关系 - attach附加(但不保存)到 Has Many

没有Access-Control-Allow-Origin标头 - Laravel

在 Laravel 中翻译特定语言