[Doctrine] Ajouter une condition like en utilisant le DQL

Publié le 08/01/2019 • Actualisé le 08/01/2019


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

L'astuce ici résidence dans le fait que l'instruction like doit être dans l'appel de la clause andWhere() alors que le caractère joker % doit être passé en paramètre à la fonction setParameter().


<?php declare(strict_types=1);

namespace App\Entity;

/**
 * @method findOneBySlug(string $slug) ?Article
 */
class ArticleRepository extends BaseRepository
{
    public function findForLang(int $type, string $lang, string $keyword = null, ?int $maxResults = null): array
    {
        $qb = $this->createQueryBuilder('a')
            ->where('a.type = :type')
            ->setParameter('type', $type)
            ->andWhere('a.inLanguage LIKE :inLanguage')
            ->setParameter('inLanguage', '%'.$lang.'%')
            ->addOrderBy('a.datePublished', 'desc');

        if (null !== $keyword) {
            $qb->andWhere('a.keyword LIKE :keyword')
            ->setParameter('keyword', '%'.$keyword.'%');
        }

        if (null !== $maxResults) {
            $qb->setMaxResults($maxResults);
        }

        return $qb->getQuery()->execute();
    }
}
En bonus, le snippet permettant d'utiliser ce code : 🎉
<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use App\Entity\Article;
use App\Enum\ArticleType;
use App\Repository\ArticleRepository;

/**
 * J'utilise un trait PHP afin d'isoler chaque snippet dans un fichier.
 * Ce code doit être apellé d'un contrôleur Symfony étendant AbstractController (depuis Symfony 4.2)
 * ou Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Les services sont injectés dans le constructeur du contrôleur principal.
 *
 * @property ArticleRepository $articleRepo
 */
trait Snippet11Trait
{
    public function snippet11(): void
    {
        $articles = $this->articleRepo->findForLang(ArticleType::SNIPPET, 'en', 'DQL');
        $article = $articles[0] ?? null;

        if (!$article instanceof Article) {
            throw new \RuntimeException('No article was found.');
        }

        echo sprintf("Article: %s\n", $article->getName() ?? '');
        echo sprintf('Keywords: %s', $article->getKeyword() ?? '');

        // That's it! 😁
    }
}

 Exécuter le snippet  Plus sur Stackoverflow  Snippet aléatoire

  Travaillez avec moi !