PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 8, 2022

[FIXED] Symfony queryBuilder: too many queries

 February 08, 2022     php, symfony, symfony-3.3     No comments   

Issue

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:

enter image description here

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...

enter image description here

How can optimize and do a single query to fetch all the records?


Solution

Explicitly create the join in your QueryBuilder, and select both the user and allowed users.

UPDATE

You must also join and select your user profile and user settings OneToOne relations because Doctrine automatically retrieves OneToOne relations any time you fetch the User entity.

The Doctrine documentation talks about why it has to perform an extra query when fetching the inverse side of a one-to-one relation.

->add('allowedUsers', EntityType::class, [
    'class' => 'AppBundle\Entity\User',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('u')
            ->select('u, au, up, us')
            ->join('u.allowedUsers', 'au')
            ->join('u.userProfile', 'up')
            ->join('u.userSettings', 'us')
            ->orderBy('u.username', 'ASC')
        ;
    },
    'label' => 'Allowed users',
    'required' => false,
    'multiple' => true
])


Answered By - Jason Roman
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing