Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select entities assuming related entity does not exist

My entity (Product) has a unidirectional many-many relation with another entity (Company) called deletedByCompanies.

I wish to select all Products that has not been deleted by a particular company. That is all products that are not connected through that many-many relation.

Tried:

$this->em->getRepository(Product::class)->createQueryBuilder('t')
->leftJoin('t.deletedByCompanies', 'deletedCompany')
->andWhere('deletedCompany.id not in (:companyId)')
->setParameter('companyId', [$companyId]);

But this simply does not return anything. Schema is pretty straghtforward:

Product:
   id: int PK

Company:
   id: int PK

DeletedProducts
   product_id: int FK
   company_id: int FK

Entity definition in Product class:

/**
 * @var Company[]
 * @ORM\ManyToMany(targetEntity="Company", indexBy="id")
 * @ORM\JoinTable(name="DeletedProducts")
 */
protected $deletedByCompanies;
like image 405
emix Avatar asked Feb 19 '26 07:02

emix


1 Answers

I think you can solve your problem with a NOT EXISTS clause on the deletedby table.

In the SQL dialect:

SELECT * FROM product p WHERE NOT EXISTS
 (SELECT * FROM DeletedProducts d WHERE p.id=d.product_id AND company_id = 2 );

In the Doctrine2 DQL, we haven't the entity DeletedProducts so we have to do a bit more stuff like:

$qb = $this->em->getRepository("AcmeDemoBundle:Product")->createQueryBuilder('t')
    ->Join('t.deletedByCompanies', 'deletedCompany')
    ->andWhere('deletedCompany.id  in (:companyId)')
    ->andWhere("p=t");

$mainQb = $this->em->getRepository("AcmeDemoBundle:Product")->createQueryBuilder('p');
$mainQb->where($mainQb->expr()->not($mainQb->expr()->exists($qb->getDQL())));
$mainQb->setParameter('companyId', [$companyId]);

var_dump($mainQb->getQuery()->getSql());
$res =$mainQb->getQuery()->execute();

Let me know if I don't understand your problem.

Hope this help

like image 100
Matteo Avatar answered Feb 22 '26 01:02

Matteo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!