我正在尝试使用Doctrine QueryBuilder来执行以下SQL查询:
DELETE php FROM product_hole_pattern php INNER JOIN hole_pattern hp ON php.hole_pattern_id = hp.id INNER JOIN hole_pattern_type hpt ON hp.hole_pattern_type_id = hpt.id WHERE php.product_id = 4 AND hpt.slug='universal';
我有这个
$qb = $this->entityManager->createQueryBuilder(); $query = $qb->delete('\SANUS\Entity\ProductHolePattern', 'php') ->innerJoin('php.holePattern', 'hp') ->innerJoin('hp.holePatternType', 'hpt') ->where('hpt.slug = :slug AND php.product=:product') ->setParameter('slug','universal') ->setParameter('product',$this->id) ->getQuery();
但我得到:
[Semantical Error] line 0, col 50 near 'hpt.slug = :slug': Error: 'hpt' is not defined.
错误消息附带的DQL是:
DELETE \SANUS\Entity\ProductHolePattern php WHERE hpt.slug = :slug AND php.product=:product
因此,连接似乎完全被省略了。
最好使用IN条件而不是迭代来运行查询。
$ids = $this->createQueryBuilder('product') ->join('..your joins..') ->where('..your wheres..') ->select('product.id') ->getQuery()->getResult(); $this->createQueryBuilder('product') ->where('product.id in (:ids)') ->setParameter('ids', $ids) ->delete() ->getQuery() ->execute();
对于激烈的“放置在哪里”的辩论,如果愿意,可以将其放在控制器中。这完全取决于您。但是,如果您将代码放入专用的学说存储库类中,那么将来对您可能会更有用。它应该很容易做,并且易于更改/维护。