简体   繁体   English

在 Laravel 的 withCount() 方法中使用 DISTINCT

[英]Use DISTINCT in Laravel's withCount() method

With Laravel/Lumen eloquent I can get count relations like this:使用 Laravel/Lumen eloquent 我可以得到这样的计数关系:

User::withCount('views')->get();

this will use SQL这将使用 SQL

select `users`.*, (select count(*) from `views` where `users`.`id` = `views`.`user_id`) as `views_count` from `users`

and return all models with views_count attribute, great.并返回所有带有 views_count 属性的模型,太好了。

But I need these views counted with unique IP column.但我需要将这些视图计入唯一 IP 列。 In this query I could simple replace count(*) with count(DISTINCT ip) like this:在这个查询中,我可以简单地将 count(*) 替换为 count(DISTINCT ip),如下所示:

select `users`.*, (select count(DISTINCT ip) from `views` where `users`.`id` = `views`.`user_id`) as `views_count` from `users`

and in phpMyAdmin it returns good results.并在 phpMyAdmin 中返回良好的结果。 But how achieve this in Laravel eloquent?但是如何在 Laravel eloquent 中实现这一点呢? I cannot find any way to use custom column for count.我找不到任何方法来使用自定义列进行计数。 I can pass array with query function like this:我可以通过这样的查询函数传递数组:

User::withCount(['views' => function ($q) { // what there? }])->get();

but now I can pass only where conditions, not use Distinct in any way.但现在我只能通过 where 条件,不能以任何方式使用 Distinct。

I know I can first get models, and then foreach with distinct and count or groupby but I need to keep this single query, fast and simple.我知道我可以先获取模型,然后使用 distinct 和 count 或 groupby 进行 foreach,但我需要保持这个单一的查询,快速而简单。 And if I can easy achieve this in raw SQL then I also should do this in Laravel somehow.如果我可以在原始 SQL 中轻松实现这一点,那么我也应该在 Laravel 中以某种方式做到这一点。 I can use some custom eloquent method if required because I will use this unique count in many places in applications.如果需要,我可以使用一些自定义的 eloquent 方法,因为我将在应用程序的许多地方使用这个唯一计数。

So short question - how to combine withCount and Distinct?这么短的问题 - 如何结合 withCount 和 Distinct?

PS I also tried to use distinct or groupBy on on model's relation level (on hasMany) but this does not work. PS我还尝试在模型的关系级别(在hasMany上)上使用distinct或groupBy,但这不起作用。

User::withCount('views', function($query) {
    $query->select(DB::raw('count(distinct(ip))'));
})->get();

Solution for Laravel 8.x Laravel 8.x 的解决方案

User::withCount(['views as views_count' => function($query) {
    $query->select(DB::raw('count(distinct(ip))'));
}])->get();

Note: Do not use selectRaw .注意:不要使用selectRaw

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

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