Laravel 在 withCount 方法上使用 where 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39930975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel using where clause on a withCount method
提问by slapbot
I am trying to do a where clause on withCount method of laravel's eloquent query builder using this piece of code.
我正在尝试使用这段代码对 laravel 的 eloquent 查询构建器的 withCount 方法执行 where 子句。
$posts = Post::withCount('upvotes')->where('upvotes_count', '>', 5)->get();
and this code is giving me this error.
这段代码给了我这个错误。
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'upvotes_count' in 'where clause' (SQL: select , (select count() from
upvotes
whereupvotes
.upvoteable_id
=posts
.id
andupvotes
.upvoteable_type
= App\Post) asupvotes_count
fromposts
whereupvotes_count
> 5)
SQLSTATE[42S22]:未找到列:1054 未知列“upvotes_count”在“where 子句”(SQL:选择,(选择 count() from
upvotes
whereupvotes
.upvoteable_id
=posts
.id
andupvotes
.upvoteable_type
= App\Post) asupvotes_count
fromposts
whereupvotes_count
> 5)
So from what I can guess is that upvotes_count isn't selected and hence the column is not being found, BUT if I execute this piece of code.
因此,我可以猜测的是 upvotes_count 没有被选中,因此没有找到该列,但是如果我执行这段代码。
$posts = Post::withCount('upvotes')->get();
Then I am getting this output.
然后我得到这个输出。
{
"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
},
Which basically means that upvotes_count is being selected, hence i am really confused about how to solve this problem.
这基本上意味着正在选择 upvotes_count,因此我对如何解决这个问题感到非常困惑。
(More options that I tried so far are given below with the respective error associated to it.)
(下面给出了我迄今为止尝试过的更多选项以及与之相关的相应错误。)
$posts = Post::where('id', $id)->withCount(['upvotes' => function($query) {
$query->where('upvotes_count', '>', 5);
}])->get();
error.
错误。
SQLSTATE[42S22]: Column not found: 1247 Reference 'upvotes_count' not supported (forward reference in item list) (SQL: select , (select count() from
upvotes
whereupvotes
.upvoteable_id
=posts
.id
andupvotes
.upvoteable_type
= App\Post andupvotes_count
> 5) asupvotes_count
fromposts
whereid
= 1)
SQLSTATE[42S22]: Column not found: 1247 Reference 'upvotes_count' not supported (forward reference in item list) (SQL: select , (select count() from
upvotes
whereupvotes
.upvoteable_id
=posts
.id
andupvotes
.upvoteable_type
= App\Post andupvotes_count
> 5) asupvotes_count
fromposts
其中id
= 1)
code.
代码。
$posts = Post::where('id', $id)->with(['upvotes' => function($query) {
$query->select('upvoteable_id AS upvotes_count');
}])->where('upvotes_count', '>', 5)->get();
AND
和
$posts = \App\Post::where('id', $id)->with(['upvotes' => function($query) {
$query->selectRaw('upvoteable_id AS upvotes_count');
}])->where('upvotes_count', '>', 5)->get();
error.
错误。
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'upvotes_count' in 'where clause' (SQL: select * from
posts
whereid
= 1 andupvotes_count
> 5)
SQLSTATE[42S22]:未找到列:1054 未知列“upvotes_count”在“where 子句”中(SQL:select * from
posts
whereid
= 1 andupvotes_count
> 5)
I just want to use where clause on a count() method which is in a relationship with a parent model.
我只想在与父模型有关系的 count() 方法上使用 where 子句。
回答by Medin Piranej
You can achieve requested result by using:
您可以使用以下方法获得请求的结果:
$posts = Post::withCount('upvotes')
->having('upvotes_count', '>', 5)
->get();
回答by Sean Glendinning
I'm not sure if this was implemented after your question, but you can now do it like this
我不确定这是否在您提出问题后实施,但您现在可以这样做
$posts = Post::has('upvotes','>',5)->get();
回答by Yousef Altaf
another good way to do this we can filter that separately and even assign an alias to that column name
另一个好方法,我们可以单独过滤,甚至为该列名分配一个别名
$posts = Post::withCount([
'upvotes',
'upvotes as upvotes_count' => function ($query) {
$query->where('upvotes_count', '>', 5);
}])
->get();
Now in blade you can do
现在在刀片中你可以做
$posts->upvotes_count
回答by BigMitch
I ran into the same problem, and tried the same things you did. I'm guessing there is a way to replicate the SQL generated by the withCounts call but add a way to make xxx_counts available to a where clause, but I just filtered the resulting collection instead.
我遇到了同样的问题,并尝试了与您所做的相同的事情。我猜有一种方法可以复制由 withCounts 调用生成的 SQL,但添加了一种方法使 xxx_counts 可用于 where 子句,但我只是过滤了结果集合。
$allTags = Tag::withCount('articles')->get();
$usedTags = $allTags->filter(function ($value, $key) {
return $value->articles_count > 0;
});
回答by Felipe Loge
If you need to select only rows that the counter is greater than or equal to 1 you can try the follow code:
如果您只需要选择计数器大于或等于 1 的行,您可以尝试以下代码:
$posts = Post::withCount('upvotes')
->havingRaw('upvotes_count')
->get();
I don't know if this is the best solution but it's an alternative. Another alternative would be get the posts and use array filter as mentioned in a comment above.
我不知道这是否是最好的解决方案,但它是一种替代方案。另一种选择是获取帖子并使用上面评论中提到的数组过滤器。
回答by Keith Turkowski
I think using has() is the best solution:
我认为使用 has() 是最好的解决方案:
Post::has('upvotes','>',5)->withCount('upvotes')->get()
You could also use a filter:
您还可以使用过滤器:
Post::withCount('upvotes')->get()->filter(function($post) { return $post->upvotes_count > 5; })
You could also disable strict mode in config/database.php (probably not a good idea)
您还可以在 config/database.php 中禁用严格模式(可能不是一个好主意)
'strict' => false,
Post::withCount('upvotes')->having('upvotes_count','>',5)->get()
You could also try to add a groupBy clause (using having in strict mode), but this will likely require you to include every column in your table (due to 'ONLY_FULL_GROUP_BY'), which could break things if you ever add another column to your table, and probably won't work anyway because I think you need to include 'upvotes_count' in the groupBy and it seems to be a non grouping field.
您还可以尝试添加 groupBy 子句(在严格模式下使用 have),但这可能需要您将表中的每一列都包含在内(由于“ONLY_FULL_GROUP_BY”),如果您将另一列添加到您的表中,这可能会破坏事情表,并且可能无论如何都不会工作,因为我认为您需要在 groupBy 中包含 'upvotes_count' 并且它似乎是一个非分组字段。