我正在尝试使用这段代码在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 = AppPost) 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.","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 = AppPost 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 = AppPost::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();
(编辑:92站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|