php – 使用连接删除Doctrine QueryBuilder
作者:互联网
我正在尝试使用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();
>好处:运行速度更快,无需迭代
>缺点:你无法挂钩到preRemove
至于激烈的“把它放在哪里”的辩论,如果你愿意,敢于把它放在控制器中.这完全取决于你.但是,如果将代码置于专用的doctrine存储库类中,将来可能对您更有用.它应该非常容易,并且易于更改/维护.
标签:doctrine-orm,query-builder,php,mysql 来源: https://codeday.me/bug/20190928/1825119.html