Symfony2 Doctrine + Twig查询耗时太长

时间:2016-07-14 13:55:26

标签: symfony orm doctrine-orm twig query-builder

我目前正在构建一个查询,以便在所需日期之间返回一组记录:

public function findBetweenDates(\Datetime $date1,\Datetime $date2)
{
        $date1=$date1->setTime(07,00,00);
        date_modify($date2,'+1 day');
        $date2->setTime(06,59,00);
        $qb = $this->getEntityManager()->createQueryBuilder()
            ->select('e')
            ->from("AppBundle:Movimento","e")
            ->andWhere('e.pesagem1 BETWEEN :from AND :to')
            ->setParameter('from', $date1 )
            ->setParameter('to', $date2)
            ->orderBy('e.id','DESC')

        ;
        $result = $qb->getQuery()->getResult();
        return $result;
    }

类Movimento有一些ManyToOne连接,如下所示:

class Movimento
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

  /**
  * @ORM\ManyToOne(targetEntity="Service")
  * @ORM\JoinColumn(name="service", referencedColumnName="id")
  **/
   private $service;

当我拿到记录并用树枝渲染时:

 {% for item in items %}
    <tr>
         <td>{{ item.id }} </td>
        <td>{{ item.service.name }}</td>
//#MORE CODE BELOW //

通过从另一个实体调用servico.name,我得到大量非需要的查询,以显示服务的名称而不是其id。 我们正在讨论每个响应中6k记录范围内的内容。

我想要一些帮助,如果可以使用我的查询构建器优化此查询,或者我应该将整个查询重新编写为&#34; SQL&#34;例如:

Select a.name, b.id
From service as a, movimento as b
Between bla bla bla

非常感谢任何帮助/建议。

编辑1 我在阅读此帖Symfony 2/Doctrine: How to lower the num of queries without losing the benefit of ORM?

后更改了我的查询构建器

我确实减少了175个查询到一个

$qb = $this->createQueryBuilder('e')
            ->addSelect('service')->join('e.service','service')
            ->addSelect('motorista')->join('e.motorista','motorista')
            ->addSelect('residuo')->join('e.residuo','residuo')
          //  ->from("AppBundle:Movimento","e")
            ->andWhere('e.pesagem1 BETWEEN :from AND :to')
            ->setParameter('from', $date1 )
            ->setParameter('to', $date2)
            ->orderBy('e.id','DESC')

但是页面加载大约需要8秒(其6900条记录),在检查性能后,我的新查询的响应时间是177.79毫秒,但是我的树枝+控制器正在显示剩余的7.x秒,因为它显示了pic https://gyazo.com/378b3553c87e04de68e87de3b6e0fc32 我的控制器非常简单

 public function getMovimentosAction(Request $request)
    {

        $startDate = $request->request->get('startDate');
        $endDate = $request->request->get('endDate');

        if (empty($startDate))
            $startDate = date("Y-m-d") ;
        if (empty($endDate))
            $endDate = date("Y-m-d");

        $em=$this->getDoctrine()->getRepository('AppBundle:Movimento');
        $dados=$em->findBetweenDates(new \DateTime($startDate),new \DateTime($endDate));

        return $this->render('AppBundle:Movimentos:logtable-movimento.html.twig', array(
            'items' => $dados
        ));
    }

并且我的树枝只是遍历行并将它们显示在桌子上,因为我给出了上面的部分示例。

非常感谢任何帮助/建议。

EDIT2 我的视图由ajax传递,呈现为datatable.js

<table id="example" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%">
    <thead class="dataTableHeader">
    <tr>
        <th>Talão</th>
        <th>Nº Talão</th>
        <th>Motorista</th>
        <th>Residuo</th>
        <th>Serviço</th>
        <th>Matricula</th>
        <th>1º Pesagem</th>
        <th>Peso Liquido</th>
        <th>Fluxo</th>
        <th>Circuito</th>
        <th>Verificado</th>
        <th></th>
    </tr>
    </thead>
    <tfoot class="dataTableHeader">
    <tr>
        <th>Talão</th>
        <th>Nº Talão</th>
        <th>Motorista</th>
        <th>Residuo</th>
        <th>Serviço</th>
        <th>Matricula</th>
        <th>1º Pesagem</th>
        <th>Liquido</th>
        <th>Fluxo</th>
        <th>Circuito</th>
        <th>Verificado</th>
        <th></th>
    </tr>
    </tfoot>
    <tbody>
    {% for item in items %}
    <tr>
        <td align="center"><a href="{{ path("_movimento_generate_pdf",{ id: item.id }) }}"> <i class="fa fa-print fa-2x" aria-hidden="true"></i>
            </a></td>
        <td>{{ item.id }} <a><i class="fa fa-eye" title="Visualizar Movimento" aria-hidden="true"></i></a>
        </td>
        <td>{{ item.motorista.idFuncionario }} - {{ item.motorista.nome }}</td>
        <td>{{ item.residuo.nome }}</td>
        <td>{{ item.servico.nome }}</td>
        <td>{{ item.matricula }}</td>
        <td>{{ item.pesagem1|date('Y-m-d h:m') }}</td>
        <td>{{ item.liquido }} kg</td>
        <td>{% if item.tipoMovimento == 1 %} Entrada {% else %} Saida {% endif %}</td>
        <td>{{ item.circuito.code | default(" ") }}</td>
        <td class="text-center">{% if item.enable==1 %}
                <span style="color: transparent">&nbsp;</span>
                <i class="fa fa-circle" aria-hidden="true" style="color: green"></i>
            {% else %}

                <i class="fa fa-times" aria-hidden="true" style="color: red;"></i>
            {% endif %}
        </td>
        <td class="text-center">
            <a class="btn btn-default" href="{{ path('_movimentos_edit',{ 'id' : item.id}) }}">
                <i class="fa fa-cog" title="Editar" aria-hidden="true"></i>
                <span class="sr-only">Settings</span>
            </a>
        </td>
    </tr>

    {% endfor %}


    </tbody>
</table>

和我的HTML

 $("#submitButtonQuery").click(function(event){
            event.preventDefault();
            var l = Ladda.create(this);
            l.toggle();
            $.post( "/movimentos/getList",
                $( "#formAjaxify" ).serialize())
                .done(function(data)
                {
                    $('#example').remove();

                    $("#tabelaLog").html(data);
                    oTable=$('#example').DataTable(
                        {
                            "scrollX": true,
                            responsive: true,

                            "language": {
                                "url": "http://cdn.datatables.net/plug-ins/1.10.11/i18n/Portuguese.json"
                            }
                        }
                    );
                    oTable.order( [ 0, 'desc' ] )
                        .draw();
      })
        .always(function(){
            l.toggle()})
    ;
});

1 个答案:

答案 0 :(得分:0)

只要你在&#39; Movimento&#39;之间有联系。和&#39;服务&#39;然后为每个&#39; movimento&#39;你得到的服务&#39;将被序列化。这意味着,如果您的查询返回100&#39; movimento&#39;然后与所有人一起服务&#39;将需要提取对象(100)。

如果您不希望将服务作为每个项目中的对象(AKA item.service.blahblah),那么您需要更直接的查询。

如果您使用查询构建器执行此操作,则需要以下内容:

$repository = $this->getDoctrine()
        ->getRepository('YourownBundle:Movimento'); //the main repo from which to get data

    $query = $repository->createQueryBuilder('m') // query builder on repo
        ->join('m.service', 's') // join the second object to select from
        ->select('m.id') // select everything from m objet
        ->addSelect('s.name') // select everything from service (s) object
        ->where('e.pesagem1 BETWEEN :from AND :to')
        ->setParameter('from', $date1 )
        ->setParameter('to', $date2)
        ->orderBy('e.id','DESC')

你的代码的其余部分应该是你拥有的......但是你没有序列化的对象,只有你做的选​​择(例如.m.id,s.name)