学说 2 使用太多 SQL 查询加载一对多关联与 fetch 模式急切

2022-01-16 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#temporarily-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 Query 来加载地址实体?

我正在使用:

  • 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.

相关文章