使用过多的 SQL 查询,doctrine2 加载具有 fetch 模式的一对多关联

2022-01-03 00:00:00 php symfony doctrine doctrine-orm

我正在加载一个包含许多实体的列表.
这些实体与其他实体之间存在一对多关联.
我想在一个 SQL 查询中加载所有这些其他实体(而不是对第一个列表中的每个实体进行一个查询).

I am loading a list of many entities.
These entities have a one-to-many association to other entities.
I want to load all these other entities in one single SQL query (instead of one query for every entity in the first list).

如doctrine2 文档所述:http://www.doctrine-project.org/docs/orm/2.1/en/reference/dql-doctrine-query-language.html#temporously-change-fetch-mode-in-dql 这应该可以通过EAGER"加载实现.

As discribed in the doctrine2 documentation: http://www.doctrine-project.org/docs/orm/2.1/en/reference/dql-doctrine-query-language.html#temporarily-change-fetch-mode-in-dql this should be possible with "EAGER" loading.

但它不像描述的那样工作.

but it does not work as described.

我的代码:

class User{
    /**
     * @ORMOneToMany(targetEntity="Address", mappedBy="user", indexBy="id", fetch="EAGER")
     */
    protected $addresses;
    public function __construct(){
        $this->addresses = new ArrayCollection();
    }
}

class Address{
    /**
     * @ORMManyToOne(targetEntity="User", inversedBy="addresses")
     * @ORMJoinColumns({
     *   @ORMJoinColumn(name="UserId", referencedColumnName="id")
     * })
     */
    private $user;
}

class UserRepository{
    public function findUsersWithAddresses(){
        return $this->getEntityManager()
            ->createQuery('SELECT u FROM MyBundle:User u ORDER BY u.name ASC')
            ->setFetchMode('MyBundleEntityUser', 'addresses', DoctrineORMMappingClassMetadata::FETCH_EAGER)
            ->setMaxResults(10)
            ->getResult();
    }
}

UserRepository::findUsersWithAddresses() 方法执行 11 个 SQL 查询.

The method UserRepository::findUsersWithAddresses() executes 11 SQL Queries.

如何告诉 Doctrine 只使用一个 SQL 查询来加载地址实体?

我正在使用:

  • symfony v2.0.9
  • 共同准则 2.1.4
  • doctrine-dbal 2.1.5
  • 教义 2.1.5

推荐答案

当前版本的学说不支持这个.

The current version of doctrine doesn't support this.

在doctrine2 问题跟踪器中有一个功能请求.

There is a feature request about this in the doctrine2 issue tracker.

所以我希望它能尽快实施.

So I hope it will be implemented soon.

相关文章