php - 如何减少 Doctrine 执行的查询数量?

标签 php mysql doctrine

我正在构建一个产品管理工具,其中 product可以有任意数量的 attributes , documents , features , images , videos以及单个 type , brand ,和category 。还有一些其他相关表格,但这足以说明问题。

有一个名为 ProductModel 的 Model 类包含这样的方法(为了清晰起见,减少了):

  public function loadValues() {
    //Product entity data
    $this->id = $this->entity->getId();
    $this->slug = $this->entity->getSlug();

    // One of each of these
    $this->loadType();
    $this->loadBrand();
    $this->loadCategory();

    // Arbitrary number of each of these
    $this->loadAttributes();
    $this->loadDocuments();
    $this->loadFeatures();
    $this->loadImages();
    $this->loadVideos();
    ...
  }

每个加载方法都会执行一些最终执行此方法的样板:

  public function loadEntitiesByProductId($productId=0) {

    // Get all the entities of this type that are associated with the product.
    $entities = $this->entityManager
      ->getRepository($this->entityName)
      ->findByProduct($productId);

    $instances = array();

    // Create a Model for each entity and load the data.
    foreach ($entities as $entity) {
      $id = $entity->getId();
      $instances[$id] = new $this->childClass();
      $instances[$id]->entity = $entity;
      $instances[$id]->loadValues();
    }

    return $instances;

  }

这对于相关实体是单个表的情况来说是可以的,但通常它是一个映射器。在这些情况下,我在第一个查询中获取所有映射器实体,然后我必须查询 loadValues() 中的相关实体。方法(通过 Doctrine 的 get<Entity>() 方法)。此过程的结果是大量查询(通常> 100)。我需要摆脱无关的查询,但我希望这样做不会丢失我在数据模型中使用的习惯用法。

有没有办法让entityManager更好地使用连接对这些查询进行分组?

最佳答案

我之前的方法存在一些问题:

首先,我从存储库获取实体,而不是从现有实体加载它们:

$entities = $this->entityManager
  ->getRepository($this->entityName)
  ->findByProduct($productId);

更好的是:

$method = $this->deriveGetMethod($this->entityName);
$entities = $productEntity->$method()

其次,我使用 $this->entityManager->getRespository... 检索产品实体,这对于加载小型数据集(单个表或一两个关系)效果很好,但是无法让存储库的 findBy 方法在单个查询中加载关系。解决方案是使用queryBuilder。

$qb = $this->entityManger->createQueryBuilder();
$query = $this->select('product',/*related tables*/)->/*joins etc.*/
$productEntity = $query->getSingleResult();

关于php - 如何减少 Doctrine 执行的查询数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17821507/

相关文章:

php - 如何从外部 PHP 脚本获取 WordPress 用户 ID?

php - 使用短代码从数据库中检索数据

javascript - 嵌套在多个 DIV 和 PHP 代码中的 jQuery 选择器

php - 从 strtotime 中减去时间

mysql - 从mysql中的表中转储单个记录的脚本

symfony - 禁用 Doctrine 查询缓存

javascript - Codeigniter 不从多表单页面返回第一个提交名称

c# - 在其他机器上访问数据库

php - 为 Doctrine 问题设置 utf8 字符集

php - 使用 Doctrine DBAL,如何确定更新失败?