No_name
No_name

Reputation: 2810

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();

Upvotes: 1

Views: 2381

Answers (2)

Daniel
Daniel

Reputation: 4549

I'm not entirely sure, but perhaps you should join subscriptions.

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

Alternatively, if subscription has an id, you can use that instead of the object.

Upvotes: 0

Alexey B.
Alexey B.

Reputation: 12033

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.

Upvotes: 5

Related Questions