php - Doctrine 添加了不必要的自连接

标签 php mysql symfony doctrine-orm doctrine

所以,这就是我现在面临的问题。我正在尝试从一张表中进行简单的选择,并且由于某种原因 Doctrine 在 SQL 查询中添加了自引用联接。我很确定它不会影响查询速度,但我宁愿摆脱它​​。

以下是我构建查询的方式:

    $qb = $this->createQueryBuilder('ol');

    $qb->select('o')
        ->from('ApplicationPersonBundle:Occupation', 'o')
        ->where($qb->expr()->eq('o.person', '?1'))
        ->addOrderBy('o.toYear', 'DESC')
        ->addOrderBy('o.toMonth', 'DESC')
        ;

    $qb->setParameter(1, $person);

这是 Doctrine 生成的内容:

SELECT 
  o0_.id AS id0, 
  o0_.description AS description1, 
  o0_.from_month AS from_month2, 
  o0_.from_year AS from_year3, 
  o0_.to_month AS to_month4, 
  o0_.to_year AS to_year5, 
  o0_.person_id AS person_id6, 
  o0_.company_id AS company_id7, 
  o0_.position_id AS position_id8 
FROM 
  occupation o1_, 
  occupation o0_ 
WHERE 
  o0_.person_id = ? 
ORDER BY 
  o0_.to_year DESC, 
  o0_.to_month DESC

我不知道“FROM占领o1_,占领o0_”从何而来。它甚至从不使用 o1_ 别名。

实体的有意义部分如下所示,没有自引用或其他内容:

/**
 * Occupation
 *
 * @ORM\Table(name="occupation")
 * @ORM\Entity(repositoryClass="Application\Bundle\PersonBundle\Entity\OccupationRepository")
 */
class Occupation
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var Person
 *
 * @ORM\OneToOne(targetEntity="Person")
 * @ORM\JoinColumn(name="person_id", referencedColumnName="id")
 */
protected $person;

}

最佳答案

您从职业存储库中获取的 qb 正确吗?无需为职业实体显式添加 select 或 from。所以这样的事情应该有效:

$qb = $this->createQueryBuilder('o'); // Change from o1, this is the occupation alias

$qb->
    ->where($qb->expr()->eq('o.person', '?1'))
    ->addOrderBy('o.toYear', 'DESC')
    ->addOrderBy('o.toMonth', 'DESC')
    ;

$qb->setParameter(1, $person);

关于php - Doctrine 添加了不必要的自连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33341243/

相关文章:

php - 使用 symfony4 和 doctrine 设置多个数据库时如何修复在两个数据库上运行的迁移

php - 没有 GROUP BY 子句时 SQL 计数返回错误

mysql连接两张表,得到匹配记录中非零值的字段名

symfony - FOSOAuthServerBundle:将 access_token 嵌入授权 header 中

php - 为每个序列化 ID 和 PHP

mysql - 当 000 仅转换 0 时使用求和大小写

php - Sonata 管理员覆盖服务配置

php - 对于每个输出(sql)一个不同的类

php - 反向mysqlescapestring

php - mysql查询更高效