4
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.

day9の今日は複雑な条件でレコードを絞り込む書き方を見ていきます。

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';

// priceが5000円未満でタイトルがSymfonyの本のリスト
/** @var array<Book> $books1 */
$books1 = $entityManager->getRepository(Book::class)
    ->createQueryBuilder('b') // aliasは何を設定しても良い
    ->where('b.price < :max_price')
    ->andWhere('b.title = :title_symfony')
    ->setParameter('max_price', 5000)
    ->setParameter('title_symfony', 'Symfony')
    ->getQuery()
    ->getResult()
;

https://github.com/77web/doctrine-vs-eloquent/blob/2ab2ea1c8e0863d6b4ec86620e995f8997477a53/Doctrine/Usecase/filter_by_complex_condition_01.php

  • where() を2回使うと1回目の where() が取り消されるので、AND条件を指定するときは andWhere() を使います。

Eloquent

<?php

declare(strict_types=1);

use App\Models\Book;

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

$books1 = Book::query()
    ->where('price', '<', 5000)
    ->where('title', 'Symfony')
    ->get()
;

https://github.com/77web/doctrine-vs-eloquent/blob/2ab2ea1c8e0863d6b4ec86620e995f8997477a53/Eloquent/Usecase/filter_by_complex_condition_01.php

  • where() を複数回使うとAND条件になります。
  • 条件を重ねていき、最後に get() を呼ぶことでBookモデルのCollectionを取得できます。
  • where() にフィルタ対象の項目名・フィルタ値だけを渡すと = 条件として扱われます。
4
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
4
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?