我正在尝试使用这段代码在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
whereupvotes
.upvoteable_id
=posts
.id
andupvotes
.upvoteable_type
= App\Post) asupvotes_count
fromposts
whereupvotes_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
whereupvotes
.upvoteable_id
=posts
.id
andupvotes
.upvoteable_type
= App\Post andupvotes_count
> 5) asupvotes_count
fromposts
whereid
= 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
whereid
= 1 andupvotes_count
> 5)
$posts = Post::withCount('upvotes')
->having('upvotes_count',5)
->get();