加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程 > 正文

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

发布时间:2021-03-31 05:02:05 所属栏目:编程 来源:网络整理
导读:我正在尝试使用这段代码在laravel的eloquent查询构建器的withCount方法上执行where子句. $posts = Post::withCount('upvotes')-where('upvotes_count','',5)-get(); 这段代码给了我这个错误. SQLSTATE[42S22]: Column not found: 1054 Unknown column upvote

我正在尝试使用这段代码在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();

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读