LoginSignup
1
1

More than 1 year has passed since last update.

day6の今日はid以外の項目に条件をつけてレコードを取得する方法を見ていきます。

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が1000円の本をすべて取得
$books = $entityManager->getRepository(Book::class)->findBy([
    'price' => 1000,
]);

// priceが5000円の本を1冊取得
$book = $entityManager->getRepository(Book::class)->findOneBy([
    'price' => 5000,
]);

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

  • Bookエンティティのレポジトリに対して findBy()[エンティティのフィールド名 => 絞り込みたい値] という形式の配列を渡す(複数指定可)ことで条件を満たすすべてのレコードを取得できます。
  • 同様の配列指定で条件を満たすレコードを1件だけ取得したいときはレポジトリの findOneBy() メソッドを使います。指定条件を満たすレコードが複数件あるときはそのうちの1件目を取得します。

Eloquent

<?php

declare(strict_types=1);

use App\Models\Book;

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

// priceが1000円の本をすべて取得
$books = Book::where('price', 1000)->get();

// priceが5000円の本を1冊取得
$book = Book::where('price', 5000)->first();

https://github.com/77web/doctrine-vs-eloquent/blob/fe0877e1fe4d9e5f28aabe407146166be89210dd/Eloquent/Usecase/filter_by_simple_condition.php

  • Bookモデルのstaticメソッド where() を使って条件を指定し、 get() で条件を満たすBookモデルのCollectionを取得できます。
  • 1つ目の引数にフィールド名、2つ目の引数に値を入れます。
  • where()->where() と重ねることで複数の条件を指定することができます。
  • whereで条件指定したあとで get() でなく first() を使うことで条件を満たす最初の1件のBookモデルのインスタンスを取得することができます。
1
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
1
1