In my Symfony project I have a User
entity with the following properties to define followers relation
#[ORM\ManyToMany(targetEntity: self::class, inversedBy: 'followers')]
#[ORM\JoinTable(name: "follows")]
#[ORM\JoinColumn(name: "follower_id", referencedColumnName: "id")]
#[ORM\InverseJoinColumn(name: "followed_id", referencedColumnName: "id")]
private $followedUsers;
#[ORM\ManyToMany(targetEntity: self::class, mappedBy: 'followedUsers')]
private $followers;
I am attempting to get the paginated list of a User's followers with the following query in my UserRepository
public function getPaginatedFollowersByUser(User $user, int $offset, int $limit): Paginator
{
$qb = $this->createQueryBuilder('u')
->select('u')
->innerJoin('u.followers', 'f')
->andWhere('f.id = :userId')
->setParameter('userId', $user->getId())
->setFirstResult($offset)
->setMaxResults($limit);
$paginator = new Paginator($qb, true);
return $paginator;
}
where Paginator is an instance of Doctrine\ORM\Tools\Pagination\Paginator
.
This works fine and now I want to know how many items are there in the result. In the DB there is only 1 follower defined for the user I am querying, yet $paginator->count()
and count($paginator)
both return the value 2
. When I iterate the paginator I find only 1 result, as expected.
I am not sure what I am missing or doing wrong. Is the counting of the result done in a different way?
Thank you!
NOTE: The workaround I've found so far is to use
$count = count($paginatedUsers->getIterator()->getArrayCopy());
instead of
$count = count($paginatedUsers);
It is not very elegant but it does output the expected 1
.
CodePudding user response:
I am embarrassed to say that the paginator was working perfectly fine and it was my mistake that this failed.
The DB in fact had 2 entries corresponding to this query, meaning that the result given by the paginator was in fact correct. The $offset
parameter in my query was 1
instead of the 0
that I expected, which made the first element be ignored and therefore my iterator only found 1 result but there were 2 results for the query.