【发布时间】:2017-02-17 06:19:40
【问题描述】:
我正在尝试使用这段代码对 laravel 雄辩的查询构建器的 withCount 方法执行 where 子句。
$posts = Post::withCount('upvotes')->where('upvotes_count', '>', 5)->get();
这段代码给了我这个错误。
SQLSTATE[42S22]:找不到列:1054 'where 子句'中的未知列'upvotes_count'(SQL:select ,(select count() from
upvoteswhereupvotes.@ 987654324@ =posts.id和upvotes.upvoteable_type= App\Post) asupvotes_countfrompostswhereupvotes_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.",
"created_at": "2016-10-07 13:47:48",
"updated_at": "2016-10-07 13:47:48",
"upvotes_count": 2
},
这基本上意味着 upvotes_count 被选中,因此我真的很困惑如何解决这个问题。
(到目前为止我尝试的更多选项在下面给出了与之相关的相应错误。)
$posts = Post::where('id', $id)->withCount(['upvotes' => function($query) {
$query->where('upvotes_count', '>', 5);
}])->get();
错误。
SQLSTATE[42S22]:未找到列:1247 不支持引用“upvotes_count”(项目列表中的前向引用)(SQL:select ,(select count() from
upvoteswhere @987654336 @.upvoteable_id=posts.id和upvotes.upvoteable_type= App\Post 和upvotes_count> 5) 作为upvotes_count来自posts其中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]:未找到列:1054 'where 子句'中的未知列 'upvotes_count'(SQL:select * from
postswhereid= 1 和upvotes_count> 5)
我只想在与父模型有关系的 count() 方法上使用 where 子句。
【问题讨论】:
标签: php mysql sql laravel eloquent