如何对 Laravel 中的多对多关系进行分组

How to groupBy many to many relationships in Laravel

我有这个基本的数据库模型我想按角色名称对所有用户进行分组即我想在两个集合中列出管理员用户和其他用户。

数据库模型

我试过这样做,但它只适用于一对多关系

User::with('roles’)->get()->groupBy(‘roles.name’);

使用通配符*跳过一个数组:

User::with('roles')->get()->groupBy('roles.*.name');