【问题标题】:Doctrine get some columns and associated entity学说获取一些列和关联实体
【发布时间】:2013-01-11 09:31:38
【问题描述】:

我在这里尝试做一件非常简单的事情,但似乎我还无法获得 DQL。此外,当我在其中输入“DQL”时,谷歌决定通过返回“SQL”的结果来让我的一天变得艰难。

我有一个具有各种属性的 Article 实体。其中之一是关联的图像实体:

/**
 * @ORM\ManyToOne(targetEntity="Image", inversedBy="articles")
 */
protected $image;

现在,为了防止延迟加载和它产生的不必要的加载,我想这样做得到 Article.title 和 Article.image,仅此而已!只是文章的名称及其关联的图像(整个图像实体)。

我该怎么做?我尝试了我想出的所有方法,希望某些东西确实有效,并且我能够检查为什么有效而其他东西无效,但我就是无法让它发挥作用。

这是我想出的最理智的查询版本,前提是它可以工作:

public function getTitleBackground($id)
{
    $qb = $this->createQueryBuilder('a')
               ->select('a.title, a.id', 'i')
               ->leftJoin('a.image', 'i')
               ->where('a.id = :id')
               ->setParameter('id', $id);

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

这会返回这个错误:

在渲染模板期间抛出异常(“[Semantical Error] line 0, col -1 near 'SELECT a.title,': Error: Cannot select entity through Identification variables without selection at least one root entity alias.") 在 PIFlexBlogBu​​ndle:Admin/Page:commentEdit.html.twig 第 13 行

当我在我的 ->select() 中添加 a 时,这个“修复”了,但随后它为我选择了所有文章字段,这正是我想要逃避的。

注意:我在 symfony2 存储库类中使用它。

【问题讨论】:

  • 您能否在问题上显示文章和图像实体的详细信息以及相关属性?

标签: symfony doctrine-orm


【解决方案1】:

【讨论】:

  • 非常感谢!通过阅读您给我的参考资料,我设法做到了。我自己永远不会找到它。当你不知道你在搜索什么时,很难在谷歌上找到东西:)
【解决方案2】:

感谢 AdrienBrault 的回答,我设法进行了查询。

public function getTitleBackground()
{
    // Pure DQL
    $q = $this->getEntityManager()->createQuery('SELECT partial a.{id,title} FROM PIFlexBlogBundle:Article a JOIN a.image i');

    // OOP building DQL through queryBuilder
    $qb = $this->createQueryBuilder('a')
               ->select('partial a.{id, title}')
               ->join('a.image', 'i');

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

通过查询生成器生成的原始 DQL 和 DQL 给出相同的结果。

注意,这会返回所有文章,要通过 id 获取,只需向它们添加 WHERE 子句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多