使用唯一的列名称对 Eloquent 集合中的对象进行分组
Use unique column names to group objects in an Eloquent Collection
我有一个典型 users
table 的 User
模型,其字段为 id
、first_name
、last_name
、user_name
、occupation
、password
、remember_token
、created_at
和 updated_at
.
User::all()
returns 集合中的所有用户。现在如何列出集合中 occupation
字段下的 user
对象。即我想要这个:
[
{
doctor: [
{
id: 1,
firstname: "John",
lastname: "Dalisay",
gender: "male",
email: "john@example.com",
username: "john123",
created: "2012-01-15 07:26:14",
modified: "2012-01-15 07:26:14"
},
{
id: 2,
firstname: "Jem",
lastname: "Panlilio",
gender: "male",
email: "jemboy09@example.com",
username: "jem123",
created: "2012-01-15 07:26:46",
modified: "2012-01-15 07:26:46"
}
],
engineer: [
{
id: 3,
firstname: "Jaylord",
lastname: "Bitamug",
gender: "male",
email: "jayjay@example.com",
username: "jay123",
created: "2012-01-15 07:27:04",
modified: "2012-01-15 07:27:04"
},
{
id: 4,
firstname: "Darwin",
lastname: "Dalisay",
gender: "male",
email: "dada08@example.com",
username: "dada123",
created: "2012-01-15 07:25:34",
modified: "2012-01-15 07:25:34"
}
]
} ....
]
我试过 groupBy
但没有成功。
数据库聚合无法按照您预期的方式使用所提供的示例。
要获得想要的结果,试试这个:
$users = User::all();
$groupByOccupation = array();
foreach($users as $user) {
$groupByOccupation[$user->occupation][] = $user;
}
//Now you can return your $groupByOccupation var to view or convertit to JSON
希望这对你有用。
我有一个典型 users
table 的 User
模型,其字段为 id
、first_name
、last_name
、user_name
、occupation
、password
、remember_token
、created_at
和 updated_at
.
User::all()
returns 集合中的所有用户。现在如何列出集合中 occupation
字段下的 user
对象。即我想要这个:
[
{
doctor: [
{
id: 1,
firstname: "John",
lastname: "Dalisay",
gender: "male",
email: "john@example.com",
username: "john123",
created: "2012-01-15 07:26:14",
modified: "2012-01-15 07:26:14"
},
{
id: 2,
firstname: "Jem",
lastname: "Panlilio",
gender: "male",
email: "jemboy09@example.com",
username: "jem123",
created: "2012-01-15 07:26:46",
modified: "2012-01-15 07:26:46"
}
],
engineer: [
{
id: 3,
firstname: "Jaylord",
lastname: "Bitamug",
gender: "male",
email: "jayjay@example.com",
username: "jay123",
created: "2012-01-15 07:27:04",
modified: "2012-01-15 07:27:04"
},
{
id: 4,
firstname: "Darwin",
lastname: "Dalisay",
gender: "male",
email: "dada08@example.com",
username: "dada123",
created: "2012-01-15 07:25:34",
modified: "2012-01-15 07:25:34"
}
]
} ....
]
我试过 groupBy
但没有成功。
数据库聚合无法按照您预期的方式使用所提供的示例。
要获得想要的结果,试试这个:
$users = User::all();
$groupByOccupation = array();
foreach($users as $user) {
$groupByOccupation[$user->occupation][] = $user;
}
//Now you can return your $groupByOccupation var to view or convertit to JSON
希望这对你有用。