3

I'm beginner on Symfony2.

I have a Regions-Countries-States-Cities database with more of 2,000,000 results. I have 8 entities:

Region (recursive with itself) - RegionTranslation

Country - CountryTranslation

State (recursive with itself) - StateTranslation

City - CityTranslation

The thing is that when I want to load a countries list (only 250 registers in a pulldown, for example) Symfony+Doctrine load all entities structure (all states of all countries, and all cities of all states, with their respective translations).

I think that it spends a lot of memory.

What's the correct method to do it? Can I load only Country (and translations) with this structure? Any idea?

4

2 回答 2

2

对于不相关的反对,我遇到了同样的问题。最好的办法是使用 select2 的 ajax 加载 ( http://ivaynberg.github.com/select2/ ),这将在搜索框中提供有限数量的项目,并通过在框中键入的内容缩小搜索范围。

有几件事需要编码:

一个javascript文件:

      $(document).ready(function(){
        $('.select2thing').select2({
          minimumInputLength:1
        ,width: "100%"
        ,ajax: {
          url: <<path>> + "entity/json"
         ,dataType: 'jsonp'
         ,quitMillis: 100
         ,data: function (term, page) {
         return {
            q: term, // search term
            limit: 20,
            page: page
         };
        }
    ,results: function (data, page) {
      var more = (page * 20) < data.total;
      return { results: data.objects, more: more };
    }
    }
    });

    }

控制器中的 jsonAction:

    /**
    * Lists all Thing entities return in json format
    *
    */
    public function jsonAction(Request $request)
    {
      $em = $this->getDoctrine()->getManager();
      $rep = $em->getRepository('yourBundle:Thing');
      $qb = $rep->createQueryBuilder('e');

      $limit = $request->query->get('limit');
      $current = $request->query->get('current');
      $page=$request->query->get('page');
      $queries=$request->query->get('q');
      $qarray=explode(",", $queries);

      $entities=$rep->getJSON($qarray, $page, $limit);
      $total=$rep->getJSONCount($qarray);
      $callback=$request->query->get('callback');

      return $this->render('yourBundle:Thing:json.html.twig'
         , array(
             'entities'  => $entities
            ,'callback'  => $callback
            ,'total'     => $total
         )
      );
    }

树枝模板(json.html.twig,可能定制为显示更多)

    {{callback}}(
    { "objects" :
    [
    {% for entity in entities %}
    { "id": "{{entity.id}}", "text": "{{entity}}""}
    {% if not loop.last %},{% endif %}
    {% endfor %}
    ],
     "total": {{total}}
    }
    )

变压器:

    use Symfony\Component\Form\DataTransformerInterface;
    use Symfony\Component\Form\Exception\TransformationFailedException;
    use Doctrine\Common\Persistence\ObjectManager;
    use yourBundle\Entity\Thing;

    class ThingTransformer implements DataTransformerInterface
    {
        /**
         * @var ObjectManager
         */
        private $em;

        /**
         * @param ObjectManager $em
         */
        public function __construct(ObjectManager $em)
        {
            $this->em = $em;
        }

        /**
         * Transforms an object (thing) to a string (id).
         *
         * @param  Issue|null $thing
         * @return string
         */
        public function transform($thing)
        {
            if (null === $thing) {return "";}
            if (is_object($thing) && "Doctrine\ORM\PersistentCollection"==get_class($thing)){
              $entity->map(function ($ob){return $ob->getId();});
              return implode(",",$thing->toArray());
            }
            return $thing;
        }

        /**
         * Transforms a string (id) to an object (thing).
         *
         * @param  string $id
         * @return Issue|null
         * @throws TransformationFailedException if object (thing) is not found.
         */
        public function reverseTransform($id)
        {
            if (!$id) {
                return null;
            }

            //if (is_array($id)){
              $qb=$this->em
                ->getRepository('yourBundle:Thing')
                ->createQueryBuilder('t');
              $thing=$qb->andWhere($qb->expr()->in('t.id', $id))->getQuery()->getResult();

              if (null === $entity) {
                throw new TransformationFailedException(sprintf(
                    'A thing with id "%s" does not exist!',
                    $id
                ));
            }

            return $thing;
        }
    }

使用 select2 控件的控制器必须将“em”传递给表单生成器:

  $editForm = $this->createForm(new ThingType()
     ,$entity
     ,array(
        'attr' => array(
            'securitycontext' => $sc
           ,'em'              => $this->getDoctrine()
                                      ->getEntityManager()
        )
     )
  );

并在您的表单类型中:

  if (isset($options['attr']['em'])){ $em = $options['attr']['em'];} else {$em=null;}

  $transformer = new ThingTransformer($em);
  $builder->add(
      $builder->create('thing'
         ,'hidden'
         ,array(
             'by_reference' => false
            ,'required' => false
            ,'attr' => array(
                'class' => 'select2thing'
            )
         )
      )
      ->prependNormTransformer($transformer)
  );
于 2012-11-24T03:55:48.277 回答
1

您可以尝试更改水合模式,使用数组比创建对象消耗更少的内存。

实现此目的的其他方法是使用迭代来避免内存问题:

最后我认为如果不花费大量时间和内存就无法全部加载,那么,为什么不进行多次查询来加载整个数据呢?

于 2014-01-28T17:23:33.113 回答