1

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.