facebook twitter hatena line google mixi email

Php/Symfony/Symfony2/doctrine/一括処理

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

update処理を2つ(外部キーなし)

$category = new \Acme\HelloBundle\Entity\Category();
$category->setName("3組");
$category4 = new \Acme\HelloBundle\Entity\Category();
$category4->setName("4組");
$em = $this->getDoctrine()->getEntityManager();
$em->persist($category4);
$em->persist($category);
$em->flush();
  • persistの順序通りに処理される。persistの順序を入れ替ええるとログも逆になる
[2016-12-26 18:25:38] doctrine.DEBUG: "START TRANSACTION" [] []
[2016-12-26 18:25:38] doctrine.DEBUG: INSERT INTO categorys (name) VALUES (?) {"1":"4組"} []
[2016-12-26 18:25:38] doctrine.DEBUG: INSERT INTO categorys (name) VALUES (?) {"1":"3組"} []
[2016-12-26 18:25:38] doctrine.DEBUG: "COMMIT" [] []

update処理を2つ(外部キーあり)

$category = new \Acme\HelloBundle\Entity\Category();
$category->setName("3組");
$user = new \Acme\HelloBundle\Entity\User();
$user->setName('taro');
$user->setDescription('太郎です');
$em = $this->getDoctrine()->getEntityManager();
$em->persist($user);
$em->persist($category);
$em->flush();
  • categoryを後にpersistしても外部キーを貼ってる方(category)から先に実行されるっぽい。
  • persistの順序を逆にしてもログの順序は同じだった
[2016-12-26 18:21:32] doctrine.DEBUG: "START TRANSACTION" [] []
[2016-12-26 18:21:32] doctrine.DEBUG: INSERT INTO categorys (name) VALUES (?) {"1":"3組"} []
[2016-12-26 18:21:32] doctrine.DEBUG: INSERT INTO users (name, description, category_id) VALUES (?, ?, ?) {"1":"taro","2":"太郎です","3":null} []
[2016-12-26 18:21:32] doctrine.DEBUG: "COMMIT" [] []

ループでのinsertの注意点

for ($i = 1; $i < 10; $i++) {
    $user = new \Acme\HelloBundle\Entity\User();
    $user->setName('taro');
    $user->setDescription('太郎です');
    $em->persist($user);
    $em->flush();
    $em->clear();
}

$em->clear();しないとメモリ不足になる