2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

day10の今日は、LIKE, IN, IS NULLを使った複雑な条件での絞り込みのやり方を見ていきます。

Doctrine

<?php

declare(strict_types=1);

use App\Entity\Book;
use Doctrine\ORM\EntityManagerInterface;

require __DIR__.'/../vendor/autoload.php';

/** @var EntityManagerInterface $entityManager */
$entityManager = require __DIR__.'/bootstrap.php';

// タイトルにSymfonyを含み、値段が2000,3000,4000円ぴったりである本
$qb1 = $entityManager->getRepository(Book::class)
    ->createQueryBuilder('b');
$exprHelper1 = $qb1->expr();
/** @var array<Book> $books1 */
$books1 = $qb1
    ->where($exprHelper1->like('b.title', ':title_symfony'))
    ->andWhere($exprHelper1->in('b.price', ':price_list'))
    ->setParameter('title_symfony', '%Symfony%')
    ->setParameter('price_list', [2000, 3000, 4000])
    ->getQuery()
    ->getResult()
;

// タイトルにSymfonyを含み、説明がnullである本
$qb2 = $entityManager->getRepository(Book::class)
    ->createQueryBuilder('b');
$exprHelper2 = $qb2->expr();
/** @var array<Book> $books2 */
$books2 = $qb2
    ->where($exprHelper2->like('b.title', ':title_symfony'))
    ->andWhere($exprHelper2->isNull('b.description'))
    ->setParameter('title_symfony', '%Symfony%')
    ->getQuery()
    ->getResult()
;

https://github.com/77web/doctrine-vs-eloquent/blob/fafeb5ca1beeed0e7e49aeceae387bef5afa0d31/Doctrine/Usecase/filter_by_complex_condition_02.php

  • like, in, is nullは Expr ヘルパークラスを使って指定することができます。

Eloquent

<?php

declare(strict_types=1);

use App\Models\Book;
use Illuminate\Database\Eloquent\Collection;

require __DIR__.'/../vendor/autoload.php';

// タイトルにSymfonyを含み、値段が2000,3000,4000円ぴったりである本
/** @var Collection<Book> $books1 */
$books1 = Book::query()
    ->where('title', 'like','%Symfony%')
    ->whereIn('price', [2000, 3000, 4000])
    ->get()
;

// タイトルにSymfonyを含み、説明がnullである本
/** @var Collection<Book> $books2 */
$books2 = Book::query()
    ->where('title', 'like','%Symfony%')
    ->whereNull('description')
    ->get()
;

https://github.com/77web/doctrine-vs-eloquent/blob/7ab3bfacad11d05923fdfc9b8da8ca6f59e29133/Eloquent/Usecase/filter_by_complex_condition_02.php

  • likeはwhereのoperationとして指定できます。
  • in は whereIn() という専用メソッドを使います。
  • is nullは whereNull() という専用メソッドを使います。
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?