0
0

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.

Doctrineで条件に合致するレコードがあるか確認したい

Posted at

要はRailsのexists?みたいなことをしたい。
DBに余計な負荷をかけない。

> User.exists?(name: '田中')
SELECT 1 AS one FROM `users` WHERE `users`.`name` = '田中' LIMIT 1
=> true

コード

$entityManager = $this->getDoctrine()->getManager();

$result = $entityManager->getRepository(User::class)
    ->createQueryBuilder('user')
    ->select('1')
    ->andWhere('user.name = :name')
    ->setParameter('name', $name)
    ->getQuery()->setMaxResults(1)->getOneOrNullResult();

return !is_null($result);

説明

  • select('1'): SELECT 1に対応
  • setMaxResults(1): LIMIT 1に対応
  • getOneOrNullResult(): 配列ではなく最初の1件またはNULLを返す
  • !is_null($result): 上記の「最初の1件またはNULL」を「true または false」に置換
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?