gpt4 book ai didi

php - Laravel 在 withCount 方法上使用 where 子句

转载 作者:可可西里 更新时间:2023-11-01 06:35:19 24 4
gpt4 key购买 nike

我正在尝试使用这段代码在 laravel 的 Eloquent 查询构建器的 withCount 方法上做一个 where 子句。

$posts = Post::withCount('upvotes')->where('upvotes_count', '>', 5)->get();

这段代码给我这个错误。

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'upvotes_count' in 'where clause' (SQL: select , (select count() from upvotes where upvotes.upvoteable_id = posts.id and upvotes.upvoteable_type = App\Post) as upvotes_count from posts where upvotes_count > 5)

因此据我猜测,upvotes_count 未被选中,因此未找到该列,但如果我执行这段代码。

$posts = Post::withCount('upvotes')->get();

然后我得到这个输出。

{
"id": 1,
"user_id": 15,
"title": "Voluptatum voluptas sint delectus unde amet quis.",
"created_at": "2016-10-07 13:47:48",
"updated_at": "2016-10-07 13:47:48",
"upvotes_count": 7
},
{
"id": 2,
"user_id": 2,
"title": "Molestiae in labore qui atque.",
"created_at": "2016-10-07 13:47:48",
"updated_at": "2016-10-07 13:47:48",
"upvotes_count": 2
},

这基本上意味着正在选择 upvotes_count,因此我真的很困惑如何解决这个问题。

(我到目前为止尝试过的更多选项在下面给出了与之相关的相应错误。)

$posts = Post::where('id', $id)->withCount(['upvotes' => function($query) {
$query->where('upvotes_count', '>', 5);
}])->get();

错误。

SQLSTATE[42S22]: Column not found: 1247 Reference 'upvotes_count' not supported (forward reference in item list) (SQL: select , (select count() from upvotes where upvotes.upvoteable_id = posts.id and upvotes.upvoteable_type = App\Post and upvotes_count > 5) as upvotes_count from posts where id = 1)

代码。

$posts = Post::where('id', $id)->with(['upvotes' => function($query) {
$query->select('upvoteable_id AS upvotes_count');
}])->where('upvotes_count', '>', 5)->get();

$posts = \App\Post::where('id', $id)->with(['upvotes' => function($query) {
$query->selectRaw('upvoteable_id AS upvotes_count');
}])->where('upvotes_count', '>', 5)->get();

错误。

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'upvotes_count' in 'where clause' (SQL: select * from posts where id = 1 and upvotes_count > 5)


我只想在与父模型有关系的 count() 方法上使用 where 子句。

最佳答案

您可以使用以下方式实现请求的结果:

$posts = Post::withCount('upvotes')
->having('upvotes_count', '>', 5)
->get();

关于php - Laravel 在 withCount 方法上使用 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39930975/

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