Skip to content

Use DTO in a query builder #555

@asispts

Description

@asispts

Can the following code work without manually defining the return type, i.e adding /** @var UserDto[] */?

final class Repository
{
    public function __construct(
        private EntityManagerInterface $em
    ) {
    }

    /**
     * @return UserDto[]
     */
    public function findAll(): array
    {
        $qb = $this->em->createQueryBuilder()
            ->select(\sprintf('NEW %s(u.id, u.email)', UserDto::class))
            ->from(User::class, 'u')
            ->getQuery();

        /** @var UserDto[] */
        return $qb->getResult();
    }

    public function findByEmail(string $email): ?UserDto
    {
        $qb = $this->em->createQueryBuilder()
            ->select(\sprintf('NEW %s(u.id, u.email)', UserDto::class))
            ->from(User::class, 'u')
            ->where('u.email = :email')
            ->setParameter('email', $email)
            ->getQuery();

        /** @var UserDto|null */
        return $qb->getOneOrNullResult();
    }
}

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