【发布时间】:2022-01-19 10:56:10
【问题描述】:
我有三个模型,User、Post 和 Comment。 User 和 Post 处于一对多关系中,User 和 Comment 也是如此。对于本示例,不存在Post-Comment 关系。
当我运行以下查询时
User::withCount(['posts', 'comments'])->get()
我得到了预期的结果:
[
...
App\Models\User {#3459
id: 18,
username: "Foo",
created_at: "2021-12-08 11:38:39",
updated_at: "2021-12-08 11:38:39",
posts_count: 5,
comments_count: 15,
}
...
]
我想从结果模型中删除时间戳。
我尝试将我想要的字段数组作为get 的参数(如->get(['username', 'posts_count', 'comments_count']),但结果根本没有改变。
我也尝试将get(...) 替换为select(...)->get(),但这会产生此错误:
Illuminate\Database\QueryException with message
'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts_count' in 'field list'
(SQL: select `username`, `posts_count`, `comments_count` from `users`)'
我认为这是因为聚合函数尚未执行。
所以我想出了这个解决方案
$usersWithCounts = User::withCount(['posts', 'comments'])->get()
->map(function ($item, $key) {
return $item->only(['username', 'posts_count', 'comments_count']);
});
但感觉不对:返回的集合不再由 Eloquent 模型组成,只是简单的数组。
[
...
[
username: "Foo",
posts_count: 5,
comments_count: 15,
]
...
]
正确的做法是什么?
【问题讨论】:
标签: php laravel laravel-5 eloquent