Faery
Faery

Reputation: 4650

Pagination - table with too many rows

I want to take the number of all the rows from a table in order to calculate how many pages will be there. But the problem is that the table has about 1000 rows and every time when I try to find how many are they, the computer slows down and needs restart.

I only need the number of the rows and nothing else. I tried this:

public function countRows()
{
    $q = $this->createQueryBuilder('q');

    $q->select('q.username');

    return $q->getQuery()->getSingleScalarResult();
}

but it seems to be quite slow.

Is there a better and faster way to count the rows? Or maybe another way to do the pagination, but then how to know how many pages will be there?

Upvotes: 0

Views: 304

Answers (2)

Yegor Lukash
Yegor Lukash

Reputation: 510

And if you are calculete COUNT many times, save result of method countRows() in property of this object and return it:

public function countRows()
{
    if ($this->countRowsQ === null)
    {
        $q = $this->createQueryBuilder('q');

        $q->select('COUNT(q.username)');

        $this->countRowsQ = $q->getQuery()->getSingleScalarResult();
    }

    return $this->countRowsQ;
}

Upvotes: 1

S3Mi
S3Mi

Reputation: 488

Try this:

public function countRows()
{
    $q = $this->createQueryBuilder('q');

    $q->select('COUNT(q.username)');

    return $q->getQuery()->getSingleScalarResult();
}

Your query wasn't counting but selecting all rows, which could be very slow.

Upvotes: 0

Related Questions