简体   繁体   English

Laravel 在 withCount 方法上使用 where 子句

[英]Laravel using where clause on a withCount method

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 where upvotes . upvoteable_id = posts . id and upvotes . upvoteable_type = App\\Post) as upvotes_count from posts where upvotes_count > 5) SQLSTATE [42S22]:未发现柱:1054未知列'upvotes_count'在'where子句'(SQL:选择(SELECT COUNT()upvotes其中upvotesupvoteable_id = postsidupvotesupvoteable_type =应用\\邮政)作为upvotes_count来自upvotes_count > 5 的posts

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 where upvotes . upvoteable_id = posts . id and upvotes . upvoteable_type = App\\Post and upvotes_count > 5) as upvotes_count from posts where id = 1) 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 和upvotes_count > 5) 作为来自id = 1) 的posts upvotes_count

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 where id = 1 and upvotes_count > 5) SQLSTATE[42S22]:未找到列:1054 在“where 子句”中未知列“upvotes_count”(SQL:从id = 1 和upvotes_count > 5 的posts中选择 *)


I just want to use where clause on a count() method which is in a relationship with a parent model.我只想在与父模型有关系的 count() 方法上使用 where 子句。

You can achieve requested result by using:您可以使用以下方法获得请求的结果:

$posts = Post::withCount('upvotes')
         ->having('upvotes_count', '>', 5)
         ->get();

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

我不确定这是否在您提出问题后实施,但您现在可以这样做

$posts = Post::has('upvotes','>',5)->get();

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' 并且它似乎是一个非分组字段。

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;
    });

If you need to select only rows that the counter is greater than or equal to 1 you can try the following 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.另一种选择是获取帖子并使用上面评论中提到的数组过滤器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM