【发布时间】:2018-04-23 20:44:35
【问题描述】:
以下代码:
示例 1
<td>
{% if listing.catalog is not empty %}
{% if listing.catalog.fitments is not empty %}
Y
{% else %}
N
{% endif %}
{% endif %}
</td>
在 14 秒内生成并使用了 345 个数据库查询
示例 2
<td>
{% if listing.catalog is not empty %}
{% endif %}
</td>
在 1.7 秒内生成并使用了 186 个数据库查询。
我知道,我一接触到学说就会尝试提取所有收集数据,但这非常昂贵。有没有更有效的方法来检查是否至少存在一个集合?
更新:
目录实体:
/**
* @ORM\OneToMany(targetEntity="Fitment", mappedBy="catalog", orphanRemoval=true, cascade={"persist"}, fetch="EAGER")
* @ORM\OrderBy({"createTime" = "DESC"})
*/
private $fitments;
/**
* Get fitments.
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getFitments() {
return $this->fitments;
}
装修实体:
/**
* @ORM\ManyToOne(targetEntity="Catalog", inversedBy="fitments")
* @ORM\JoinColumn(name="catalog_id", referencedColumnName="catalog_id")
*/
private $catalog;
【问题讨论】:
-
另一种方法是将
empty($object)测试移动到控制器中,并且只将非空对象传递给模板。 -
我认为它仍然会运行相同数量的查询,但它将在控制器中完成。不?我只需要检查集合是否包含任何数据。如果我可以在实体级别甚至查询构建器上使用 findOneBy 而不是 findAll。
-
您应该使用自定义查询并手动获取附加字段,即使 186 个查询听起来也太多了。