Skip to content

Postgres ->count() always returns 1 when grouping #17406

Closed
@davzie

Description

@davzie
  • Laravel Version: 5.3.29
  • PHP Version: 7.1
  • Database Driver & Version: PostgreSQL 9.6.1 on x86_64-apple-darwin16.1.0, compiled by Apple LLVM version 8.0.0 (clang-800.0.42.1), 64-bit

Description:

Laravel will always return 1 when you try to call the ->count() method on a query that is being grouped. See below.

Steps To Reproduce:

If I want to get the amount of users in a system who have posted an article I might want to do something like this:

$userPostCount = DB::table('posts')
                                ->whereNotNull('user_id')
                                ->groupBy('user_id')
                                ->groupBy('id')
                                ->count();

But this will always return 1. At least whilst testing, I had 7 posts, each with a unique user_id but the query above will return 1.

As a result, I've had to get around this by doing:

$userPostCount = DB::table('posts')
                                ->whereNotNull('user_id')
                                ->groupBy('user_id')
                                ->groupBy('id')
                                ->select('user_id')
                                ->get()->unique('user_id')->count();

I don't mind doing this, but obviously at scale I'm pulling all records here and having to then count those which can't be too good. I would switch to MySQL but Postgres is kinda shitty about that.

I also posted this on #14123

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions