简体   繁体   中英

How to groupBy many to many relationships in Laravel

I have this basic database model I would like to group all users by role name ie I want to list the users who are admins and the others in two collections.

Database model

在此处输入图像描述

I tried to do this but it only works for one to many relationships

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

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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