OK, firstly, your User - Group relationship is not defined correctly. You need add ManyToOne relationships:
/** * @var \AppBundle\Entity\Group * * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Group") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="group_id", referencedColumnName="id") * }) */ private $group;
A few words about this. In the JoinColumns by default, the relation is null, which means that you can have NULL instead of the foreign key in the resulting group_id column (the join column that Doctrine will create for you).
If you want to have a relation other than zero, the definition should look like this:
/** * @var \AppBundle\Entity\Group * * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Group") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="group_id", referencedColumnName="id", nullable=false) * }) */ private $group;
So, by default, you can have a NULL group for User . Once this is determined correctly, regarding your questions:
1.
If your application is created correctly, you should never end up with a User associated with a Group that has not yet been bound to a database. Each Group that you bind to User must be delivered from the Doctrine in some way before continuing to use User . Whether from the application or from the form. If you need to verify that a Group exists before continuing with User , you must solve the problem upstream, and are 100% sure that any Group that you use is taken from the database.
In this particular context, the setGroup installer should already ensure that what is provided is indeed a Group object (if you must not add typehint), and Doctrine already ensures that this object already exists in the database. I agree that Doctrine errors can become ugly, but the supplied product should by no means include any of them.
Understand that Symfony authentication is typically used with forms in order to check for potential violations entered by the end user, not the developer (usually).
2.
With the right relationship, as shown above, Doctrine will take care of this automatically for you. By default, all Doctrine relationships load lazily.
also:
public function getGroup() { try { $group = $this->group; } catch (\Doctrine\ORM\EntityNotFoundException $e) { $group = null; } return $group; }
You do not need to do this. Remove it.