0

I have a User entity with One To Many relation such as this:

/**
 * @ORM\OneToMany(targetEntity="UserMarket", mappedBy="user")
 * @var Collection|UserMarket[]
 */
private Collection $userMarkets;

This User object is returned by simple UserProvider class which ensures the User is indeed the class I want it to be:

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Security;
class UserProvider
{
    /**
     * @var Security
     */
    private Security $security;
    /**
     * @var EntityManagerInterface
     */
    private EntityManagerInterface $entityManager;

    public function __construct(Security $security, EntityManagerInterface $entityManager)
    {
        $this->security = $security;
        $this->entityManager = $entityManager;
    }


    public function getUser(): User
    {
        $repository = $this->entityManager->getRepository(User::class);
        $user = $this->security->getUser();
        if ($user instanceof User) {
            return $user;
        }

        /** @var User $dbUser */
        $dbUser = $repository->findOneBy(['username' => $user->getUsername()]);
        return $dbUser;
    }
}

When I get the User inside of a Type class (needed to tighten results to only user related data), the userMarkets collection is always empty, despite there is UserMarket object related to it in database.
What is curious about that, is that in the database tab of profiler I can see that all the data was queried properly (id of non-existent userMarket was used to get further related objects).
What is more curious is that when I added fetch="EAGER" to annotation, the collection is filled properly. I don't understand why it isn't when fetch is lazy, so I guessed there would be some unforeseen consequences down the line. And there was.. With fetch="EAGER" I get an error while trying to authorize :

Notice: serialize(): "" returned as member variable from __sleep() but does not exist

I don't quite know, what part of the code might be important here. Please advise, what am I doing wrong?

Jeroen
  • 1,991
  • 2
  • 16
  • 32
Arkadiusz Galler
  • 305
  • 3
  • 18
  • 1
    How did you verify the UserMarket collection is indeed empty? When you, for example, dump the User object the collection will nog be initialized and stays empty. Collections are by default Lazy and will be initialized when you start to access it, by calling the getter for example or looping over it. If you still think something is wrong, please add the code where the collection is empty. – Jeroen May 16 '20 at 10:23
  • I think a problem was with caching, because after rearranging the code (without changing it) it started to work. Thanks for the tip about uninitialized collection while dumping the User object. I have been doing it wrong, will pay closer attention to this next time :) Thank you :) – Arkadiusz Galler May 16 '20 at 19:08

0 Answers0