larvel mysql count_php – Laravel在withCount方法上使用where子句

我正在尝试使用这段代码在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.","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子句,该方法与父模型有关系.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值