I have an entity with a ManyToMany relationship with the User table:
/**
* @ORM\ManyToMany(targetEntity="User")
* @ORM\JoinTable(
* name="offer_allowedusers",
* joinColumns={
* @ORM\JoinColumn(name="offer_id", referencedColumnName="id", onDelete="CASCADE")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
* }
* )
*/
private $allowedUsers;
And, in the form, I want to display a dropdown (using select2) to select which users are allowed:
To do that, I made, in the Form building:
->add('allowedUsers', EntityType::class, [
'class' => 'AppBundle\Entity\User',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.username', 'ASC');
},
'label' => 'Allowed users',
'required' => false,
'multiple' => true
])
The problem is that it makes a query for each user, to get the username... So if I have 500 users, it makes 500 queries...
How can optimize and do a single query to fetch all the records?
$this->username
. Without that it wouldn't display the usernames in the dropdown – Impassable'choice_label' => 'username'
in the form builder options array? – Cambell[it makes a query for each user, to get the username]
shouldn't, theEntityType
execute this query just one time, theusername
is retrieved for each iteration of the result. github.com/symfony/symfony/blob/… – Pinnacle@ORM\OneToOne(targetEntity="UserProfile", mappedBy="user", fetch="EXTRA_LAZY")
– ImpassableLAZY
orEXTRA_LAZY
setting to change that. But, you can join them as well in your QueryBuilder. see my answer for what should work. – OratoriouserProfile
join statement to the query builder. – Pinnacle