【问题标题】:How to groupBy many to many relationships in Laravel如何在 Laravel 中对多对多关系进行分组
【发布时间】:2022-01-01 13:36:48
【问题描述】:

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

数据库模型

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

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

【问题讨论】:

    标签: php mysql laravel database eloquent


    【解决方案1】:

    使用通配符* 跳过数组:

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

    【讨论】:

    • 稍微解释一下通配符 (*) 跳过了什么会很好。
    • 假设数据透视表 role_user 包含列“类型”。我们如何按此列对用户进行分组?
    • @AhmedIbrahimMeraneh 将->withPivot('type') 添加到roles User 模型的关系并使用groupBy('roles.*.pivot.type')
    猜你喜欢
    • 1970-01-01
    • 2019-10-02
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    相关资源
    最近更新 更多