はじめに
SymfonyでORM(Doctrine)を使用したCRUD操作が初めてでした。忘れないためにアウトプットしようと思い記事にしました。
※分かりやすくするためにソースコードはシンプルに書いております。
※ORM(Doctrine)については軽く過去の記事で紹介しています。
参考:Doctrineで接続しているRDBMSの名前取得(ORMの説明)
ちなみにCRUD操作とは
ちなみにCRUD操作とは、データの作成(Create)、読み出し(Read)、更新(Update)、削除(Delete)の頭文字を繋げた言葉です。
参考:CRUD(Wikipedia)
その前に
リポジトリについて記述しようかと思います。リポジトリは読み出し(Read)、更新(Update)、削除(Delete)で使用します。
リポジトリは下記サイトにこのような記述があります。
When you query for a particular type of object, you always use what's known as its "repository". You can think of a repository as a PHP class whose only job is to help you fetch entities of a certain class.
Once you have a repository object, you have many helper methods:
参考:Symfony docs:fetching-objects-from-the-database
つまり、リポジトリはあるクラスの実体を取得するためのPHPクラスであり、リポジトリオブジェクトを取得して読み出しや更新、削除ができるようになります。
CRUD
今回は商品クラス(Product)を例に書いていきます。
変数の$id
は主キーのことです。
データの作成(Create)
$product = new Product();
$product->setName("机");
$product->setPrice(1000);
$entityManager->persist($product);
$entityManager->flush();
データの読み出し(Read)
データの読み出しは方法はいくつかありますので紹介します。
また、findだけはリポジトリオブジェクトとエンティティマネージャの2パターンで読み出しができるので記述しました。
find
findは指定した主キーのデータを取得します。
// リポジトリオブジェクトを使用した場合
$productRepository = $entityManager->getRepository(Product::class);
$productRepository->find($id);
// エンティティマネージャを使用した場合
$entityManager->find(Product::class, $id);
findAll
findAllは全てのデータを取得します。
$productRepository = $entityManager->getRepository(Product::class);
$productRepository->findAll();
findOneBy
findOneByは第一引数にカラムと値の配列を与えることでデータを取得できます。
$productRepository = $entityManager->getRepository(Product::class);
$productRepository->findOneBy(array('name'=>'机'));
findBy
findByは第一引数にカラムと値の配列を与えることでデータを取得できます。
また、第二引数~第四引数に値を入れることで取得できるデータが変わります。第二引数は並び順(昇順、降順)、第三引数は取得数、第四引数は何番目からデータを取得するか等です。
※第二引数~第四引数は別に値を入れなくてもよいです。
※こちらのページを参考にしました。doctrine-project:by-simple-conditions
$productRepository = $entityManager->getRepository(Product::class);
$productRepository->findBy(array('name'=>'机'),array('price'=>'DESC'),2,2); // findBy(array("column"=>"value"), $orderBy, $limit, $offset)
データの更新(Update)
$productRepository = $entityManager->getRepository(Product::class);
$product = $productRepository->find($id);
$product->setName("デスク");
$entityManager->persist($product);
$entityManager->flush();
データの削除(Delete)
※こちらのページが参考になります。doctrine-project:removing-entities
$productRepository = $entityManager->getRepository(Product::class);
$product = $productRepository->find($id);
$entityManager->remove($product);
$entityManager->flush();
参考文献
CRUD(Wikipedia)
doctrine-project:Getting Started with Doctrine
Symfony docs:fetching-objects-from-the-database
doctrine-project:by-simple-conditions
doctrine-project:removing-entities