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

前端之家收集整理的这篇文章主要介绍了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子句,该方法与父模型有关系.

最佳答案
您可以使用以下方法获得请求结果:

$posts = Post::withCount('upvotes')
         ->having('upvotes_count',5)
         ->get();
原文链接:https://www.f2er.com/mysql/433528.html

猜你在找的MySQL相关文章