【问题标题】:Doctrine QueryBuilder - Exclude articles linked to specific themesDoctrine QueryBuilder - 排除链接到特定主题的文章
【发布时间】:2014-08-04 14:31:56
【问题描述】:

我正在使用 Doctrine2 进行 Symfony2 项目。

我有一个多对多关系的“文章”和“主题”表。 我正在尝试获取除与主题 35 相关的文章之外的所有文章。

$query = $this->createQueryBuilder('art')
        ->join('art.themes', 'the')
        ->where('the != '.35)
        ->getQuery()
        ->getResult();

仅当我的文章只有一个主题时,此请求才有效。如果文章有多个(例如主题 35 + 主题 36),则不会从结果中排除。

我该如何解决这个问题?

这是我想在 SQL 中使用的请求:

SELECT id, title, theme_id FROM article, article_theme WHERE article.id = article_theme.article_id AND 35 NOT IN (SELECT theme_id FROM article_theme WHERE article_id = article.id);

感谢您的帮助!

【问题讨论】:

  • 你能像这样检索你想要的结果吗? $res = $this->getDoctrine()->getRepository()->findBy(array('theme_id' != 35));
  • 文章上没有“theme_id”字段,我正在使用第三个表(文章 article_theme 主题)

标签: php symfony doctrine-orm dql doctrine-query


【解决方案1】:

我最终做了这样的事情:

// First we get all the articles with theme 35
$qbFirstStep = $this->getEntityManager()->createQueryBuilder();

$qbFirstStep->select('aa.id')
    ->from('AP\NewsBundle\Entity\Article', 'aa')
    ->leftJoin('aa.themes', 'the')
    ->where('the.id = 35');

// Then we get all articles where article.id not in ids of the first request
$qbFinal = $this->getEntityManager()->createQueryBuilder();

$qbFinal->select('bb')
    ->from('AP\NewsBundle\Entity\Article', 'bb')
    ->where($qbFinal->expr()->notIn('bb.id', $qbFirstStep->getDQL()));

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

当然不是最干净的方法,但它确实有效

【讨论】:

    猜你喜欢
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    相关资源
    最近更新 更多