Programming

findAll Doctrine의 방법을 정렬하는 방법

procodes 2020. 8. 19. 21:15
반응형

findAll Doctrine의 방법을 정렬하는 방법


나는 Doctrine의 문서를 읽고 있었지만 findAll () 결과를 정렬하는 방법을 찾지 못했습니다.

나는 symfony2 + doctrine을 사용하고 있습니다. 이것은 컨트롤러 내부에서 사용하고있는 진술입니다.

$this->getDoctrine()->getRepository('MyBundle:MyTable')->findAll();

하지만 결과가 오름차순 사용자 이름으로 정렬되기를 원합니다.

이 방법으로 배열을 인수로 전달하려고했습니다.

findAll( array('username' => 'ASC') );

그러나 그것은 작동하지 않습니다 (그것도 불평하지 않습니다).

DQL 쿼리를 작성하지 않고이를 수행 할 수있는 방법이 있습니까?


@Lighthart와 같이 컨트롤러에 상당한 지방을 추가하고 건조하지는 않지만 가능합니다.

엔터티 리포지토리에서 자신의 쿼리를 정의해야합니다. 간단하고 모범 사례입니다.

use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository
{
    public function findAll()
    {
        return $this->findBy(array(), array('username' => 'ASC'));
    }
}

그런 다음 저장소에서 쿼리를 찾도록 엔티티에 지시해야합니다.

/**
 * @ORM\Table(name="User")
 * @ORM\Entity(repositoryClass="Acme\UserBundle\Entity\Repository\UserRepository")
 */
class User
{
    ...
}

마지막으로 컨트롤러에서 :

$this->getDoctrine()->getRepository('AcmeBundle:User')->findAll();

$this->getDoctrine()->getRepository('MyBundle:MyTable')->findBy([], ['username' => 'ASC']);

단순한:

$this->getDoctrine()->getRepository('AcmeBundle:User')->findBy(
    array(),
    array('username' => 'ASC')
);

때때로 소스 코드를 보는 것이 유용합니다.

예를 들어 findAll구현은 매우 간단합니다 ( vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php).

public function findAll()
{
    return $this->findBy(array());
}

그래서 우리는 findBy우리에게 필요한 것을보고 찾습니다. ( orderBy)

public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)

이것은 나를 위해 작동합니다.

$entities = $em->getRepository('MyBundle:MyTable')->findBy(array(),array('name' => 'ASC'));

첫 번째 배열을 비워두면 모든 데이터를 가져 오지만 제 경우에는 작동했습니다.


Doctrine API 소스 코드를 살펴보십시오.

class EntityRepository{
  ...
  public function findAll(){
    return $this->findBy(array());
  }
  ...
}

다음과 같은 기준을 사용해야합니다.

<?php

namespace Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Collections\Criteria;

/**
* Thing controller
*/
class ThingController extends Controller
{
    public function thingsAction(Request $request, $id)
    {
        $ids=explode(',',$id);
        $criteria = new Criteria(null, <<DQL ordering expression>>, null, null );

        $rep    = $this->getDoctrine()->getManager()->getRepository('Bundle:Thing');
        $things = $rep->matching($criteria);
        return $this->render('Bundle:Thing:things.html.twig', [
            'entities' => $things,
        ]);
    }
}

배열 반복기를 사용하여 기존 ArrayCollection을 정렬 할 수 있습니다.

$ collection이 findAll ()에 의해 반환 된 ArrayCollection이라고 가정합니다.

$iterator = $collection->getIterator();
$iterator->uasort(function ($a, $b) {
    return ($a->getPropery() < $b->getProperty()) ? -1 : 1;
});
$collection = new ArrayCollection(iterator_to_array($iterator));

이것은 findAllOrderBy () 메소드를 생성하기 위해 저장소에 넣을 수있는 함수로 쉽게 변환 될 수 있습니다.


nifr을 작성한 솔루션의 대안을 사용합니다.

$resultRows = $repository->fetchAll();
uasort($resultRows, function($a, $b){
    if ($a->getProperty() == $b->getProperty()) {
        return 0;
    }
    return ($a->getProperty()< $b->getProperty()) ? -1 : 1;
});

ORDER BY보다 빠르고 Iterator의 오버 헤드가 없습니다.


이 시도:

$em = $this->getDoctrine()->getManager();

$entities = $em->getRepository('MyBundle:MyTable')->findBy(array(), array('username' => 'ASC'));

findBy method in Symfony excepts two parameters. First is array of fields you want to search on and second array is the the sort field and its order

public function findSorted()
    {
        return $this->findBy(['name'=>'Jhon'], ['date'=>'DESC']);
    }

Modify the default findAll function in EntityRepository like this:

public function findAll( array $orderBy = null )
{
    return $this->findBy([], $orderBy);
}

That way you can use the ''findAll'' on any query for any data table with an option to sort the query

참고URL : https://stackoverflow.com/questions/17116888/how-to-sort-findall-doctrines-method

반응형