如何在 laravel 的 withCount 中添加 having 子句?
How to add having clause to withCount in laravel?
我想获取包含 2022-05-12 23:59:59
之前创建的评论总数的帖子。我也有附加的时区过滤器。我尝试了以下方法:
Route::get('/', function () {
$base = Post::withCount([
'comment' => function ($query) {
$query->select(
'id',
'post_id',
DB::raw('convert_tz(created_at, "UTC", "US/Eastern") as created_at_tz')
)->having('created_at_tz', '<=', '2022-05-12 23:59:59')->count();
},
]);
return $base->get();
});
我收到错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts.id' in 'where clause'
select
count(*) as aggregate
from
(
select
convert_tz(created_at, "UTC", "US/Eastern") as created_at_tz
from
`comments`
where
`posts`.`id` = `comments`.`post_id`
having
`created_at_tz` <= 2022 -05 -12 23: 59: 59
) as `temp_table`
我做错了什么?
...
->withCount([
'comment' => function ($query) {
$query->whereRaw('convert_tz(created_at, "UTC", "US/Eastern") <= '2022-05-12 23:59:59'));
}])
...
试试这个并用回复更新我
我认为最后没有必要计数
我想获取包含 2022-05-12 23:59:59
之前创建的评论总数的帖子。我也有附加的时区过滤器。我尝试了以下方法:
Route::get('/', function () {
$base = Post::withCount([
'comment' => function ($query) {
$query->select(
'id',
'post_id',
DB::raw('convert_tz(created_at, "UTC", "US/Eastern") as created_at_tz')
)->having('created_at_tz', '<=', '2022-05-12 23:59:59')->count();
},
]);
return $base->get();
});
我收到错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts.id' in 'where clause'
select
count(*) as aggregate
from
(
select
convert_tz(created_at, "UTC", "US/Eastern") as created_at_tz
from
`comments`
where
`posts`.`id` = `comments`.`post_id`
having
`created_at_tz` <= 2022 -05 -12 23: 59: 59
) as `temp_table`
我做错了什么?
...
->withCount([
'comment' => function ($query) {
$query->whereRaw('convert_tz(created_at, "UTC", "US/Eastern") <= '2022-05-12 23:59:59'));
}])
...
试试这个并用回复更新我
我认为最后没有必要计数