gpt4 book ai didi

php - 具有预加载的 Laravel 分组

转载 作者:搜寻专家 更新时间:2023-10-31 21:26:00 25 4
gpt4 key购买 nike

我想通过预加载实现一些分组

当我做这样的事情时:

$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') 但我想保留上面的相同查询以免进行另一个查询调用

如果不可能。还有其他解决方法吗?

最佳答案

是的,你可以做到这一点

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

关于php - 具有预加载的 Laravel 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36064449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com