alexjumperman/doctrinetemptable

该软件包最新版本(1.0.1)没有提供许可信息。

Doctrine 2 临时表扩展

安装: 11

依赖: 0

建议者: 0

安全: 0

星标: 1

关注者: 1

分支: 0

公开问题: 0

类型:symfony-bundle

1.0.1 2018-11-11 16:18 UTC

This package is not auto-updated.

Last update: 2024-09-24 20:13:18 UTC


README

问题

让我们想象我们有一个包含100万产品的在线商店。在某个特定的分类页面,我们只需要处理整个库存中的100个产品,并且我们需要得到

  1. 该页面上的总产品数量
  2. 按某种顺序排序的前10个产品实体
  3. 按每个单独的筛选条件的产品数量等。

对整个库存的查询将不会有效。更有效的方法是将所需产品选择到临时表中,并从临时表中执行这些查询。

安装

composer require alexjumperman/doctrinetemptable

使用方法

1. 使用存储库特质

<?php

namespace AppBundle\Repository;

use AlexJumperman\TempTableBundle\Utils\TempTableTrait;

class ProductRepository extends \Doctrine\ORM\EntityRepository
{
    use TempTableTrait;
}

使用特质后,我们继续在控制器中操作

<?php

namespace AppBundle\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        $qb = $this->get('doctrine.orm.entity_manager')
            ->getRepository('AppBundle:Product')
            ->createQueryBuilderForTempTable('p');
    }
}

2. 或者我们可以使用服务工厂

<?php

namespace AppBundle\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        $repository = $this->get('doctrine.orm.entity_manager')->getRepository('AppBundle:Product');
        $qb = $this->get('alex_jumperman_temp_table.factory')
            ->createQueryBuilderForTempTable($repository, 'p');
    }
}

工作流程

当我们有临时表的查询构建器实例时,我们需要根据我们的要求构建它。在我们的例子中,我们需要选择与特定分类相关联的所有产品。

$qb->where('p.category_id = 1');

在配置查询构建器后,我们可以创建我们的临时表的存储库。实际上,它将是Doctrine存储库的某种类似物,用于处理临时表存储。

$tempRepository = $qb->createTempTableRepository('temp_products_table');

当临时存储库创建后,我们可以配置查询以选择必要的数据。

$result1 = $tempRepository
            ->getEntityManager()
            ->getConnection()
            ->fetchColumn($tempRepository->createQueryBuilder('p')->select('count(p)')->getSQL());
$result2 = $tempRepository
            ->createQueryBuilder('p')
            ->setMaxResults(10)
            ->orderBy('p.price')
            ->getQuery()
            ->getResult();

整个过程示例

<?php

namespace AppBundle\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        $repository = $this->get('doctrine.orm.entity_manager')->getRepository('AppBundle:Product');
        $tempRepository = $this->get('alex_jumperman_temp_table.factory')
            ->createQueryBuilderForTempTable($repository, 'p')
            ->where('p.category_id = 1')
            ->createTempTableRepository('temp_products_table');
        $result1 = $tempRepository
            ->getEntityManager()
            ->getConnection()
            ->fetchColumn($tempRepository->createQueryBuilder('p')->select('count(p)')->getSQL());
        $result2 = $tempRepository
            ->createQueryBuilder('p')
            ->setMaxResults(10)
            ->orderBy('p.price')
            ->getQuery()
            ->getResult();
    }
}