gpt4 book ai didi

symfony - 如果未设置表关系,如何使用查询生成器连接 Doctrine2 中的两个表?

转载 作者:行者123 更新时间:2023-12-04 23:27:43 26 4
gpt4 key购买 nike

我目前正在使用 Symfony2 和 Doctrine2,并尝试使用查询构建器将两个表连接在一起。

我遇到的问题是我所有带注释的实体都没有设置表关系。我会在某个时候解决这个问题,但同时我需要尝试解决这个问题。

基本上我有两个表:一个产品表和一个 product_description 表。 product 表存储基本信息,然后我有一个 product_description 表存储描述信息。由于语言的原因,产品可以有一个或多个描述。

我想使用查询构建器,因此我可以将 product 和 product_description 结果作为对象进行检索。

目前我正在使用以下代码:

// Get the query builder
$qb = $em->createQueryBuilder();

// Build the query
$qb->select(array('p, pd'));
$qb->from('MyCompanyMyBundle:Product', 'p');
$qb->innerJoin('pd', 'MyCompanyMyBundle:ProductDescription', 'pd', 'ON', $qb->expr()->eq('p.id', 'pd.departmentId'));
$query = $qb->getQuery();
$products = $query->getResult();

这给了我以下错误:
[Syntax Error] line 0, col 71: Error: Expected Doctrine\ORM\Query\Lexer::T_DOT, got 'MyCompanyMyBundle:ProductDescription'

任何人都可以指出我正确的方向吗?如果有其他选择,我愿意以不同的方式来做。

最佳答案

如果没有定义关系,我认为您无法加入表格。这是因为当您使用 DQL 时,您查询的是一个对象而不是一个表,如果这些对象彼此不知道,您就无法加入它们。

我认为您应该考虑使用 NativeQuery。来自 docs :

A NativeQuery lets you execute native SELECT SQL statements, mapping the results according to your specifications. Such a specification that describes how an SQL result set is mapped to a Doctrine result is represented by a ResultSetMapping. It describes how each column of the database result should be mapped by Doctrine in terms of the object graph. This allows you to map arbitrary SQL code to objects, such as highly vendor-optimized SQL or stored-procedures.



基本上,您编写原始 SQL,但告诉 Doctrine 如何将结果映射到您现有的实体。

希望这可以帮助。

关于symfony - 如果未设置表关系,如何使用查询生成器连接 Doctrine2 中的两个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9890540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com