Doctrine2でUPDATEするときのサンプルってfindしてEntityオブジェクトを取得してremoveする方法が一般的に紹介されている方法だと思います。
1
2
3
4
5
6
7
8
9
|
<?php
$em = $this->getDoctrine()->getEntityManager();
$post = $em->find('HogeFugaBundle:Post', $id);
if (!$post) {
throw new NotFoundHttpException('データがありません');
}
$em->remove($post);
$em->flush();
?>
|
一つのデータを消すのにはこれぐらいでもちょうどいいんですが、100行とか、1000行のレコードを削除するときはこの方法はよいアプローチだと思いません。
じゃあどのようなアプーチが良いのか?以下のようにQueryBuilderを利用すれば簡単にデータの削除ができます。
たとえば、ブログの指定したユーザーの投稿をすべて削除する場合にこのような書き方ができます。
1
2
3
4
5
6
7
|
<?php
$em = $this->getDoctrine()->getEntityManager();
$em->createQueryBuilder()
->delete("Blog","b")
->where('b.user_id = :user_id')
->setParameter('user_id', 1);
?>
|
このコードをしらないと、無駄なコードが多くなってしまうので覚えておくと良いかと思います。
また、deleteができるならupdateもできるわけですよ。
1
2
3
4
5
6
7
8
|
<?php
$em = $this->getDoctrine()->getEntityManager();
$em->createQueryBuilder()
->update("Blog","b")
->set("b.category", 2)
->where('b.user_id = :user_id')
->setParameter('user_id', 1);
?>
|
これで無駄ならループや、無駄にEntityオブジェクトを生成しないのでメモリの節約にもなりますね!!