【发布时间】:2018-10-03 08:10:31
【问题描述】:
鉴于此代码,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 = ?
这些是实体:
TABLE1:主要实体,女巫通过 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 中的每行一个,witch 通过 oneToMany 与 table1 相关联并通过 ManyToMany 使用 table3。
其他相关点是 querybuilder 正在 SonataAdmin query_builder 字段选项下执行。
我找不到为什么会出现这种行为,有什么线索吗?
【问题讨论】:
-
这是任何 ORM 的标准行为。阅读如何使用Collections in Doctrine。
-
好吧,我知道 manyToMany 水合涉及查询两个实体之间的中间表,但这不是 ORM 所做的,它是获取其中一个表中的所有数据并检索尽可能多的数据对象作为表格具有的行,这就是我不明白的。事实上,当我对已经通过内部连接获取的数据进行 where 时,查询就完成了。
-
查询不是查询本身的结果,而是视图中对象图遍历的结果。
标签: php mysql symfony doctrine