Programing

Laravel Eloquent-distinct () 및 count ()가 함께 제대로 작동하지 않음

lottogame 2020. 10. 17. 09:01
반응형

Laravel Eloquent-distinct () 및 count ()가 함께 제대로 작동하지 않음


그래서 나는 쿼리에서 구별되는 pid의 수를 얻으려고하는데 반환 값이 잘못되었습니다.

이것이 내가하려는 것입니다.

$ad->getcodes()->groupby('pid')->distinct()->count()

값 "2"를 리턴하는 것은 리턴해야하는 값이 "1"이어야합니다.

해결 방법으로 다음을 수행합니다.

count($ad->getcodes()->groupby('pid')->distinct()->get())

잘 작동하고 "1"을 반환하는 것

개수와 구별이 동일한 쿼리에있을 수없는 규칙이 있습니까? "무거움"의 해결 방법을 찾았습니다. 원래 쿼리가 작동하도록 만들고 싶습니다.


다음이 작동합니다.

$ad->getcodes()->distinct('pid')->count('pid');

저와 다른 사람들을 절약 할 수있는보다 일반적인 답변 :

작동하지 않음 (모든 행의 수를 반환) :

DB::table('users')
            ->select('first_name')
            ->distinct()
            ->count();

수정 사항 :

DB::table('users')
            ->distinct()
            ->count('first_name');

다른 사람이이 게시물을보고 다른 제안을 찾지 못하셨습니까?

특정 쿼리에 따라 다른 접근 방식이 필요할 수 있습니다. 제 경우에는 GROUP BY, 예를 들어

SELECT COUNT(*) FROM (SELECT * FROM a GROUP BY b)

또는 사용 COUNT(DISTINCT b):

SELECT COUNT(DISTINCT b) FROM a

약간의 수수께끼 끝에 나는 이들 중 하나에 내장 된 Laravel 함수가 없다는 것을 깨달았습니다. 따라서 가장 간단한 해결책은 방법을 사용하는 것 DB::raw입니다 count.

$count = $builder->count(DB::raw('DISTINCT b'));

groupBy전화하기 전에 사용하지 마십시오 count. groupBy행을 가져 오는 데 필요한 경우 나중에 신청할 수 있습니다 .


비슷한 문제가 있었고 해결 방법을 찾았습니다.

문제는 Laravel의 쿼리 빌더가 집계를 처리하는 방식입니다. 반환 된 첫 번째 결과를받은 다음 '집계'값을 반환합니다. 일반적으로 괜찮지 만 count를 groupBy와 결합하면 그룹화 된 항목 당 개수를 반환합니다. 따라서 첫 번째 행의 집계는 첫 번째 그룹의 개수 일뿐입니다 (따라서 1 또는 2와 같이 낮은 값일 가능성이 높습니다).

그래서 Laravel의 개수가 나오지 않았지만 Laravel 쿼리 빌더를 원시 SQL과 결합하여 그룹화 된 결과의 정확한 개수를 얻었습니다.

귀하의 예를 들어, 다음이 작동해야한다고 기대합니다 (그리고 얻을 수 없도록).

$query = $ad->getcodes()->groupby('pid')->distinct();
$count = count(\DB::select($query->toSql(), $query->getBindings()));

모든 열을 선택하는 데 시간을 낭비하지 않으려면 쿼리를 작성할 때이를 피할 수 있습니다.

 $query = $ad->select(DB::raw(1))->getcodes()->groupby('pid')->distinct();

나는 같은 문제를 만났다.

laravel 디버그 바를 설치하면 쿼리를 볼 수 있으며 종종 문제를 볼 수 있습니다.

$ad->getcodes()->groupby('pid')->distinct()->count()

로 변경

$ad->getcodes()->distinct()->select('pid')->count()

You need to set the values to return as distinct. If you don't set the select fields it will return all the columns in the database and all will be unique. So set the query to distinct and only select the columns that make up your 'distinct' value you might want to add more. ->select('pid','date') to get all the unique values for a user in a day


Wouldn't this work?

$ad->getcodes()->distinct()->get(['pid'])->count();

See here for discussion..


Distinct do not take arguments as it adds DISTINCT in your sql query, however, you MAY need to define the column name that you'd want to select distinct with. Thus, if you have Flight->select('project_id')->distinct()->get() is equialent to SELECT DISTINCT 'project_id' FROM flights and you may now add other modifiers like count() or even raw eloquent queries.


$solution = $query->distinct()
            ->groupBy
            (
                [
                    'array',
                    'of',
                    'columns',
                ]
            )
            ->addSelect(
                [
                    'columns',
                    'from',
                    'the',
                    'groupby',
                ]
            )
            ->get();

Remember the group by is optional,this should work in most cases when you want a count group by to exclude duplicated select values, the addSelect is a querybuilder instance method.


You can use the following way to get the unique data as per your need as follows,

$data = $ad->getcodes()->get()->unique('email');

$count = $data->count();

Hope this will work.


Try the following:

$ad->getcodes()->groupby('pid')->distinct()->get()->count()

This was working for me so Try This: $ad->getcodes()->distinct('pid')->count()


DB::table('adverts')->distinct()->select('ad_advertiser')->get()

try this

$ad->getcodes()->groupby('pid')->distinct()->count('pid')

참고URL : https://stackoverflow.com/questions/28651727/laravel-eloquent-distinct-and-count-not-working-properly-together

반응형