Home > Net >  How to order by entity property in symfony?
How to order by entity property in symfony?

Time:05-30

I'm trying to get the "demands" of a user.

User can have some demands and a demand have only one user (OneToMany)

This is my User entity (Utilisateur in french) :

class Utilisateur extends AbstractEntity implements UserInterface, PasswordAuthenticatedUserInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="ulid", unique=true)
     * @ORM\GeneratedValue(strategy="CUSTOM")
     * @ORM\CustomIdGenerator(class=UlidGenerator::class)
     */
    private Ulid $id;

    /**
     * @ORM\OneToMany(targetEntity=DemandeTransport::class, mappedBy="utilisateur", orphanRemoval=true)
     */
    private Collection $demandeTransports;

And my demands entity :

class DemandeTransport extends AbstractEntity
{
    /**
     * @ORM\Id
     * @ORM\Column(type="ulid", unique=true)
     * @ORM\GeneratedValue(strategy="CUSTOM")
     * @ORM\CustomIdGenerator(class=UlidGenerator::class)
     */
    private Ulid $id;

    /**
     * @ORM\ManyToOne(targetEntity=Utilisateur::class, inversedBy="demandeTransports")
     * @ORM\JoinColumn(nullable=false)
     */
private Utilisateur $utilisateur;

My controller receiving the request :

/**
 * @throws Exception
 */
#[Route('/liste_propositions_transporteur', name: 'liste_propositions_transporteur', methods: ['GET'])]
public function listePropositionsTransporteur(Request $request): Response
{
    return match ($request->getMethod()) {
        'GET' => new Response(json_encode(['success' => true, 'data' => $this->propositionsTransportService->handleListePropositionsByUser($this->getUser())])),
        default => new Response(404),
    };
}

The service handling the request and retreiving the demands :

/**
 * @param UserInterface $user
 * @return array
 */
public function handleListePropositionsByUser(UserInterface $user) : array
{
    $propositions = [];
    foreach ($this->propositionTransportRepository->findPropositionsByUtilisateur($user) as $propositionTransport) {
        $propositions[] = DemandeTransportHelper::serializePropositionDemande($propositionTransport);
    }

    return $propositions;
}

And the DQL :

/**
 * @param UserInterface $user
 * @return mixed
 */
public function findPropositionsByUtilisateur(UserInterface $user) : mixed
{
    $q = $this->createQueryBuilder('p')
        ->where('p.utilisateur = :utilisateur')
        ->setParameters([
            'utilisateur' => $user
        ])
        ->orderBy('p.dateCreation', 'DESC');

    return $q->getQuery()->getResult();
}

So : When i'm doing $utilisateur->getDemandesTransports() : it works by showing me all the demands.

Well, but when I'm trying to get them by DQL (cause I want them orderd by), it returns me 0 results...

CodePudding user response:

Solved by setting the parameter type :

->setParameter('utilisateur', $utilisateur->getId(), 'ulid')

I'm using ULID (UUID like) on IDs. https://symfony.com/doc/current/components/uid.html#working-with-ulids

CodePudding user response:

With annotations

You can order your data by specifying sorting in your $demandeTransports property annotations.

/**
 * @ORM\OneToMany(targetEntity=DemandeTransport::class, mappedBy="utilisateur", orphanRemoval=true)
 * @ORM\OrderBy({"dateCreation" = "DESC"})
 */
private Collection $demandeTransports;

So when you call $utilisateur->getDemandesTransports() you will get ordered data.

With DQL

Also if you still want to use DQL then you should change your query to this as you need to join the Utilisateur entity then you can use the desired properties

   $q = $this->createQueryBuilder('p')
        ->join('p.utilisateur', 'u')
        ->where('u.utilisateur = :utilisateur')
        ->setParameters([
            'utilisateur' => $user
        ])
        ->orderBy('u.dateCreation', 'DESC'); 
  • Related