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

php – Laravel在withCount要领上行使where子句

发布时间:2021-03-31 07:37:35 所属栏目:编程 来源:网络整理
导读:我正在实行行使这段代码在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();

(编辑:湖南网)

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

    热点阅读