Search code examples
symfonyrepositorymany-to-manylimitrelationship

Symfony2 - Many to Many relationship and LIMIT


Im use many-to-many relationship;

User entity;

/**
 * @ORM\ManyToMany(targetEntity="Conversation", inversedBy="users")
 */
protected $conversations;

Conversation entity;

/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="conversations")
 * @ORM\JoinTable(name="user_conversation")
 */
protected $users;

When, I work this function;

$user->getConversations();

Symfony work this sql code in background;

SELECT 
  t0.id AS id1, 
  t0.conversationid AS conversationid2 
FROM 
  Conversation t0 
  INNER JOIN user_conversation ON t0.id = user_conversation.conversation_id 
WHERE 
  user_conversation.user_id = ?

And select all conversation. This will be performance problem. So, I work with repository class. But, I can't work many-to-many and limit function with together. What should I do? What I write to repository class?


Solution

  • If you want to optimize access to large collections in doctrine just use Criteria (That only works on OneToMany associations.)

    Example:

    use Doctrine\ORM\Mapping as ORM;
    use Doctrine\Common\Collections\Criteria;
    
    /**
     * @ORM\Entity
     * @ORM\Table
     */
    class User
    {
        ....
    
        public function getLatestConversation()
        {
            $criteria = Criteria::create()
                ->setMaxResults(10);
    
            return $this->conversations->matching($criteria);
        }
    }
    

    For ManyToMany I think you must create a custom query:

    public function getLatestConversations($user)
    {
        $qb = $this->createQueryBuilder("c");
        $qb
            ->leftjoin("c.users", "u")
            ->where("u = :user")
            ->setParameter("user", $user)
            ->setMaxResults(2);
    
        return $qb->getQuery()->getResult();
    }