Query indexBy with OneToOne relation result in nullable TKey

Open
#422 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
42/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
php
Domain
devtools

Research direction

Start with commit 4490e56f6fe3f8985a03be073d4545c3fb59cdb and the unit test added there, then compare its plain string or int indexBy coverage with the reported OneToOne relation query. Reproduce the array<int|null, Something> result and add coverage for this relationship case; done means the valid non-null key is inferred without the reported error.

Written by the indexing model from the issue text.

Description

It works fine with version 1.3.28 but since version 1.3.29 with this commit https://github.com/phpstan/phpstan-doctrine/commit/4490e56f6fe3f8985a03be073d4545c3fb59cdbb , when using a query builder with indexBy refering to a OneToOne relation, I get the error

Method SomethingRepository::getAllIndexedByUsers() should return array<int, Something> but returns array<int|null, Something>.

The userId column in my table something is not nullable, it's literally the primary key

My entities are defined as follow

#[ORM\Entity]
class Something
{
    #[ORM\OneToOne, ORM\Id]
    private readonly User $user;

    #[Column]
    private int $value = 1;

    public function __construct(User $user) {
        $this->user = $user;
    }
}
#[ORM\Entity]
class User
{
    #[ORM\Column, ORM\Id, ORM\GeneratedValue]
    private int $id;

    #[Column]
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }
}

and the query

    /**
     * @param list<User> $users
     *
     * @return array<int, Something>
     */
    public function getAllIndexedByUsers(array $users): array
    {
        return $this->entityManager->getRepository(Something::class)
            ->createQueryBuilder('something', 'something.user')
            ->where('something.user IN (:users)')->setParameter('users', $users)
            ->getQuery()
            ->getResult();
    }

I see in the unit test added in the commit that it's not tested with relationship, only with plain string or int column

Dominant language
PHP
Stars
678
Forks
122
Avg merge
5d 18h
Merged PRs (30d)
3

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from phpstan/phpstan-doctrine

All issues in phpstan/phpstan-doctrine

Similar issues

More PHP issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.