gpt4 book ai didi

php - Doctrine 使用内部 Join 启动过多查询

转载 作者:行者123 更新时间:2023-11-29 06:38:42 25 4
gpt4 key购买 nike

根据这段代码,Doctrine 会启动与 table2 中的行一样多的查询

$qb = $this->getModelManager()->createQuery($er->getClassName(), 't1')->getQueryBuilder();

$qb->select('t1, t2, t3')
->innerJoin('table1.table2', 't2');
->innerJoin('table2.table3', 't3')
->where('t3.id = :foo')
->setParameter('foo', $foo);

每个查询都是这样的:

SELECT t0.id AS id_1,
t0.name AS name_2,
t0.slug AS slug_3,
t0.description AS description_4,
t0.visible AS visible_5
FROM table2 t0
WHERE t0.id = ?

这些是实体:

表1:主要实体,女巫通过manyToOne与表2相关,如果我与表2进行innerJoin,Doctrine按预期行事(1个查询)

/**
* @ORM\Entity(repositoryClass = "Table1Repo")
* @ORM\Table(name="table1")
*/
class table1 extends BaseTable1 implements table1Interface
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
protected $id;

/**
* @ORM\Column(type="string", length=255)
* @Gedmo\Versioned
*/
protected $name;

/**
* @ORM\ManyToOne(targetEntity="table2", inversedBy="tables1")
* @ORM\JoinColumn(name="table2_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $table2;
}

TABLE2,通过 OneToMany 与表 1 相关,通过 ManyToMany 与表 3 相关。

/**
* @ORM\Entity(repositoryClass="table2Repository")
* @ORM\Table(name="table2")
*/
class table2 extends Basetable2
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
protected $id;

/**
* @ORM\ManyToMany(targetEntity="table3", inversedBy="table2s")
* @ORM\JoinTable(name="table3_table2")
*/
protected $table3;

/**
* @ORM\OneToMany(targetEntity="table1", mappedBy="table2")
* @Accessor(getter="getTables1")
*/
protected $tables1;
}

TABLE3:仅通过多对多关系与表 2 相关。当我使用表 2 进行 innerJoin 时,Doctrine 仍然按预期运行,仅进行一个查询

/**
* @ORM\Entity(repositoryClass = "table3Repo")
* @ORM\Table(name="table3")
* @Gedmo\Loggable
*/
class table3 extends Basetable3
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
protected $id;

/**
* @ORM\ManyToMany(targetEntity="table2", mappedBy="tables3")
* @ORM\JoinTable(name="table3_table2")
*/
protected $tables2;
}

因此,当我将两个innerJoins添加到查询构建器时,Doctrine只进行一个查询,但是当我添加WHERE子句时,当Doctrine进行279个查询时,table2中每行一个,女巫通过oneToMany与table1相关以及ManyToMany 的table3。

其他相关点是,querybuilder 正在 SonataAdmin query_builder 字段选项下执行。

我找不到为什么会出现这种行为,有什么线索吗?

最佳答案

当您运行查询时,您始终需要有一个连接到其他实体的根实体。在您的例子中,即table1。获取后,根据查询和实体元数据,Doctrine 将尝试为每个 root 实例创建一个对象,但除非另有说明,它将停在那里。事实上,对于每个子对象(例如table2),它将创建虚拟“代理”对象,这些对象只是浅层表示,并且每当尝试取消引用它们时都将从数据库中解析。将数据库结果转换为对象的过程称为对象水化。

为了对子对象执行水合,您还需要“选择”子实体:

$qb->select('t1', 't2', 't3')
->innerJoin('t1.table2', 't2');
->innerJoin('t2.table3', 't3')
->where('t3.id = :foo')
->setParameter('foo', $foo);

注意不要疯狂地获取所有内容,因为它需要更长的时间并且消耗更多的内存。微调您的查询,直到达到您想要的结果(逻辑和性能方面)。

希望这有帮助...

关于php - Doctrine 使用内部 Join 启动过多查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52622580/

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