Laravel分组急切加载

时间:2016-03-17 15:06:35

标签: php json laravel laravel-5 eager-loading

我希望通过热切加载实现一些分组

当我做这样的事情时:

$usersWithDepartments = User::with('department')->get();

出来了:

[
    {
        "userID": 491,
        "userName": "gigi"
        "deparment": 
        {
            "departmentID": 1,
            "name": "Economy"
        }
    },
    {
        "userID": 444,
        "userName": "gigi2"
        "deparment": 
        {
            "departmentID": 1,
            "name": "Economy"
        }
    }
]

但我想知道是否可以这样做:

$usersWithDepartments = User::with('department')->groupBy('deparment')->get();

为了得到像这样的JSON:

[
    {
        "departmentID": 1,
        "name": "Economy",
        "users":
        [
            {
                "userID": 491,
                "userName": "gigi"            
            },
            {
                "userID": 444,
                "userName": "gigi2"            
            }            
        ]
    }
]

我知道我可以做Department::with('users')但我想保留上面相同的查询,以便不再进行其他查询调用

如果不可能的话。还有其他工作吗?

1 个答案:

答案 0 :(得分:1)

是的,你可以这样做

$usersWithDepartments = User::with('department')->groupBy('departmentID');
     $usersWithDepartments->toJson();