Search code examples
phpsqlsymfonydoctrine-ormarraycollection

Doctrine where clause with an array


I have an entity called "invoice" with many "subscription" such that "invoice" and "subscription" are in a many to many relationship.

class Invoice
{
/**
 * @ORM\Column(type="integer")
 */
protected $a;

/**
 * @ORM\Column(type="integer")
 */
protected $b;

/**
 * @ORM\ManyToMany(targetEntity="Subscription", inversedBy="invoices")
 */
protected $subscriptions;

public function __construct()
{
    $this->subscriptions = new ArrayCollection();
}

//typical setters and getters
}

Using the querybuilder, how do I get a set of matching entities using the where clause on subcription?

$subscription = ;//something pulled from the db and is a "subscription" object
$em->createQueryBuilder()
            ->select('p')
            ->from('Invoice', 'p')
            ->where('p.a = :a')
            ->andWhere('p.b = :b')
            ->andWhere('p.subscriptions has :subscription')   //this line here I need help
            ->setParameter('a', 1)
            ->setParameter('b', 2)
            ->setParameter('subscription', $subscription)
            ->getQuery()
            ->getResult();

Solution

  • Doctrine have special statement MEMBER OF for this aim. Another solution is to make subquery.

    ->andWhere(':subscription MEMBER OF p.subscriptions') 
    

    Examples you can find in official doctrine documentation.