我正在尝试使用这段代码对 laravel 雄辩的查询构建器的 withCount 方法执行 where 子句。
$posts = Post::withCount('upvotes')->where('upvotes_count', '>', 5)->get();
这段代码给了我这个错误。
SQLSTATE [42S22]:未找到列:1054 ‘where 子句’中的未知列’upvotes_count’(SQL:选择,(从
upvotes
选择计数( )upvoteable_id
其中upvotes
---
=posts
.id
andupvotes
.upvoteable_type
= App\Post) asupvotes_count
fromposts
其中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]:找不到列:1247 不支持引用“upvotes_count”(项目列表中的前向引用)(SQL:选择,(从
upvotes
选择计数( )—其中upvotes
。upvoteable_id
=posts
.id
andupvotes
.upvoteable_type
= App\Post andupvotes_count
> 5) 作为upvotes_count
来自posts
其中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]:未找到列:1054 ‘where 子句’中的未知列 ‘upvotes_count’(SQL:select * from
posts
其中id
= 1 和upvotes_count
> 5)
我只想在与父模型有关系的 count() 方法上使用 where 子句。
原文由 slapbot 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用以下方法实现请求的结果: