Symfony2 - Doctrine DQL - 选择与另一个表行无关的行

时间:2016-12-19 18:19:32

标签: sql symfony doctrine-orm doctrine dql

我有两个表OfferOfferSuggestion,其FOREIGN_KEYOffer相关。我希望获得与Offer的任何行尚未关联的OfferSuggestion行。

优惠:

id      name
1       offer1
2       offer2

OfferSuggestion:

id    offer_id   name
1     2          suggestion2

在这种情况下,我应该得到没有建议的offer1

到目前为止,我已尝试过此操作,但无效:

$query = 'SELECT o FROM IndexBundle:Offer o '.
    'WHERE NOT EXISTS ('.
    'SELECT s.offer FROM IndexBundle:OfferSuggestion s '.
    'WHERE o.id = s.offer)';
$query = $em->createQuery($query);

我收到错误:

  

[语义错误]第0行,第91列附近提供FROM   IndexBundle:OfferSuggestion':错误:无效的PathExpression。必须是   StateFieldPathExpression。

我缺少什么想法?

2 个答案:

答案 0 :(得分:2)

您可以简单地引用对象实例,如下所示:

$query = 'SELECT o FROM IndexBundle:Offer o '.
    'WHERE NOT EXISTS ('.
    'SELECT s FROM IndexBundle:OfferSuggestion s '.
    'WHERE o = s.offer)';

您还可以使用querybuilder创建子查询:

例如,仅用于演示HOW-TO在select语句中使用子查询select语句,假设我们找到所有尚未编译地址的用户(地址表中不存在任何记录):

 // get an ExpressionBuilder instance, so that you
$expr = $this->_em->getExpressionBuilder();

// create a subquery in order to take all address records for a specified user id
$sub = $this->_em->createQueryBuilder()
    ->select('a')
    ->from($this->_addressEntityName, 'a')
    ->where('a.user = u.id');


$qb = $this->_em->createQueryBuilder()
    ->select('u')
    ->from($this->_userEntityName, 'u')
    ->where($expr->not($expr->exists($sub->getDQL())));

return $qb->getQuery()->getResult();

答案 1 :(得分:1)

这是否有效:

$query = 'SELECT o FROM IndexBundle:Offer o '.
    'WHERE NOT IN ('.
    'SELECT s.offer_id FROM IndexBundle:OfferSuggestion s '.
    'WHERE o.id = s.offer_id)';

我只是猜测,但你可以尝试一下吗?