覆盖默认标识符生成策略对关联没有影响

Taz*_*Taz 8 php oop associations symfony doctrine-orm

Symfony 2.7.2.Doctrine ORM 2.4.7.MySQL 5.6.12.PHP 5.5.0.
我有一个具有自定义ID生成器策略的实体.它完美无瑕.
在某些情况下,我必须用"手工制作"ID覆盖此策略.它在主要实体被刷新而没有关联时起作用.但它不适用于协会.抛出此示例错误:

使用params ["a004r0",4]执行'INSERT INTO articles_tags(article_id,tag_id)VALUES(?,?)'时发生异常:

SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(sf-test1.articles_tags,CONSTRAINT FK_354053617294869CFOREIGN KEY(article_id)REFERENCES article(id)ON DELETE CASCADE)

以下是如何重现:

  1. 安装并创建Symfony2应用程序.
  2. app/config/parameters.yml使用数据库参数进行编辑.
  3. 使用示例AppBundle命名空间,在目录中创建ArticleTag实体src/AppBundle/Entity.

    <?php
    // src/AppBundle/Entity/Article.php
    namespace AppBundle\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * @ORM\Entity
     * @ORM\Table(name="article")
     */
    class Article
    {
        /**
         * @ORM\Column(type="string")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="CUSTOM")
         * @ORM\CustomIdGenerator(class="AppBundle\Doctrine\ArticleNumberGenerator")
         */
        protected $id;
    
        /**
         * @ORM\Column(type="string", length=255)
         */
        protected $title;
    
        /**
         * @ORM\ManyToMany(targetEntity="Tag", inversedBy="articles" ,cascade={"all"})
         * @ORM\JoinTable(name="articles_tags")
         **/
        private $tags;
    
        public function setId($id)
        {
            $this->id = $id;
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
    <?php
    // src/AppBundle/Entity/Tag.php
    namespace AppBundle\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    use Doctrine\Common\Collections\ArrayCollection;
    
    /**
     * @ORM\Entity
     * @ORM\Table(name="tag")
     */
    class Tag
    {
        /**
         * @ORM\Column(type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue
         */
        protected $id;
    
        /**
         * @ORM\Column(type="string", length=255)
         */
        protected $name;
    
        /**
         * @ORM\ManyToMany(targetEntity="Article", mappedBy="tags")
         **/
        private $articles;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 为上述实体生成getter和setter:

    php app/console doctrine:generate:entities AppBundle
    
    Run Code Online (Sandbox Code Playgroud)
  5. 创建ArticleNumberGeneratorsrc/AppBundle/Doctrine:

    <?php
    // src/AppBundle/Doctrine/ArticleNumberGenerator.php
    namespace AppBundle\Doctrine;
    use Doctrine\ORM\Id\AbstractIdGenerator;
    use Doctrine\ORM\Query\ResultSetMapping;
    
    class ArticleNumberGenerator extends AbstractIdGenerator
    {
        public function generate(\Doctrine\ORM\EntityManager $em, $entity)
        {
            $rsm = new ResultSetMapping();
            $rsm->addScalarResult('id', 'article', 'string');
            $query = $em->createNativeQuery('select max(`id`) as id from `article` where `id` like :id_pattern', $rsm);
            $query->setParameter('id_pattern', 'a___r_');
            $idMax = (int) substr($query->getSingleScalarResult(), 1, 3);
            $idMax++;
            return 'a' . str_pad($idMax, 3, '0', STR_PAD_LEFT) . 'r0';
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  6. 创建数据库:php app/console doctrine:database:create.

  7. 创建表:php app/console doctrine:schema:create.
  8. 编辑DefaultController位于的示例AppBundle src\AppBundle\Controller.将内容替换为:

    <?php
    // src/AppBundle/Controller/DefaultController.php
    namespace AppBundle\Controller;
    
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    
    use AppBundle\Entity\Article;
    use AppBundle\Entity\Tag;
    
    class DefaultController extends Controller
    {
        /**
         * @Route("/create-default")
         */
        public function createDefaultAction()
        {
            $tag = new Tag();
            $tag->setName('Tag ' . rand(1, 99));
    
            $article = new Article();
            $article->setTitle('Test article ' . rand(1, 999));
            $article->getTags()->add($tag);
    
            $em = $this->getDoctrine()->getManager();
    
            $em->getConnection()->beginTransaction();
            $em->persist($article);
    
            try {
                $em->flush();
                $em->getConnection()->commit();
            } catch (\RuntimeException $e) {
                $em->getConnection()->rollBack();
                throw $e;
            }
    
            return new Response('Created article id ' . $article->getId() . '.');
        }
    
        /**
         * @Route("/create-handmade/{handmade}")
         */
        public function createHandmadeAction($handmade)
        {
            $tag = new Tag();
            $tag->setName('Tag ' . rand(1, 99));
    
            $article = new Article();
            $article->setTitle('Test article ' . rand(1, 999));
            $article->getTags()->add($tag);
    
            $em = $this->getDoctrine()->getManager();
    
            $em->getConnection()->beginTransaction();
            $em->persist($article);
    
            $metadata = $em->getClassMetadata(get_class($article));
            $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
            $article->setId($handmade);
    
            try {
                $em->flush();
                $em->getConnection()->commit();
            } catch (\RuntimeException $e) {
                $em->getConnection()->rollBack();
                throw $e;
            }
    
            return new Response('Created article id ' . $article->getId() . '.');
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  9. 运行服务器:php app/console server:run.

  10. 导航到http://127.0.0.1:8000/create-default.刷新2次以查看此消息:

    创建文章ID为a003r0.

  11. 现在,导航到http://127.0.0.1:8000/create-handmade/test.预期的结果是:

    创建文章ID test1.

    但相反,你会得到错误:

    使用params ["a004r0",4]执行'INSERT INTO articles_tags(article_id,tag_id)VALUES(?,?)'时发生异常:

    SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(sf-test1.articles_tags,CONSTRAINT FK_354053617294869CFOREIGN KEY(article_id)REFERENCES article(id)ON DELETE CASCADE)

    显然因为id"a004r0"的文章不存在.

如果我注释掉$article->getTags()->add($tag);createHandmadeAction,它的工作原理-结果是:

创建文章ID测试.

并相应地更新数据库:

id     | title
-------+----------------
a001r0 | Test article 204
a002r0 | Test article 12
a003r0 | Test article 549
test   | Test article 723
Run Code Online (Sandbox Code Playgroud)

但不是在添加关系时.出于某种原因,Doctrine不使用手工制作id的关联,而是使用默认的Id生成器策略.

这有什么不对?如何说服实体经理使用我手工制作的ID进行关联?

ori*_*nal 6

您的问题与$em->persist($article);更改ClassMetadata.

在新的实体持续UnitOfWork产生idArticleNumberGenerator它保存到entityIdentifiers现场。稍后在填充关系表行的ManyToManyPersister帮助下使用此值PersistentCollection

在调用时flush UoW计算实体的更改集并保存实际的 id 值 - 这就是为什么在添加关联后获得正确数据的原因。但它不会更新entityIdentifiers.

要解决此问题,您只需persist更改 ClassMetadata 对象即可。但方式仍然看起来像黑客。IMO 更优的方法是编写自定义生成器,如果提供或生成新的,则该生成器将使用分配的 id。

附注。应该考虑的另一件事 - 您生成 id 的方式不安全,它会在高负载时产生重复的 id。

UPD MissedUoW不使用idGeneratorType(元数据工厂使用它来设置正确的idGenerator值)所以你应该设置正确idGenerator

/**
 * @Route("/create-handmade/{handmade}")
 */
public function createHandmadeAction($handmade)
{
    $tag = new Tag();
    $tag->setName('Tag ' . rand(1, 99));

    $article = new Article();
    $article->setTitle('Test article ' . rand(1, 999));
    $article->getTags()->add($tag);

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

    $em->getConnection()->beginTransaction();

    $metadata = $em->getClassMetadata(get_class($article));
    $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
    $metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());
    $article->setId($handmade);

    $em->persist($article);

    try {
        $em->flush();
        $em->getConnection()->commit();
    } catch (\RuntimeException $e) {
        $em->getConnection()->rollBack();
        throw $e;
    }

    return new Response('Created article id ' . $article->getId() . '.');
}
Run Code Online (Sandbox Code Playgroud)

这像预期的那样工作。