【问题标题】:How to set an initial auto_increment value using doctrine2如何使用教义 2 设置初始 auto_increment 值
【发布时间】:2011-12-22 18:50:16
【问题描述】:

我使用doctrine2 映射器来生成我的innoDB (mysql) 数据库。 如何使用 php 注释设置我的 auto_incremented id 的初始值?

这就是我目前为我的实体类型的 id 建模的方式。

/**
 * @var integer $_id
 *
 * @Column(name="id", type="integer", nullable=false)
 * @Id
 * @GeneratedValue(strategy="IDENTITY")
 */
private $_id;

我在文档中找到了以下代码,但它看起来好像会使用单独的表来生成 ID。

/**
 * @Id
 * @GeneratedValue(strategy="SEQUENCE")
 * @Column(type="integer")
 * @SequenceGenerator(sequenceName="tablename_seq", initialValue=1, allocationSize=100)
 */

【问题讨论】:

    标签: php mysql doctrine-orm


    【解决方案1】:

    您可以设置 strategy="NONE" 并在 @prepersist 函数中设置最后一个 ID。更简单的方法是添加一个“ALTER TABLE something AUTO_INCREMENT = 100;”在 DataFixture 或 DB 迁移中。它不是可移植的 SQL,但它可以在不增加实体复杂性的情况下完成这项工作。

    【讨论】:

    • prepersist 函数中如何设置 id?
    • 在 prepersist 中获得最高的 +1,但要使用事件管理器
    • 竞态条件如何?我认为按照您的建议,它必须通过事务来完成,如果一次性创建多个实体(例如在安装脚本中)我认为您会遇到问题,不是吗?
    • 好吧,我首选的解决方案是将其放入数据库迁移或固定装置中
    • 我在 Symfony2 项目中使用了固定装置。你可以在这里阅读所有内容symfony.com/doc/2.0/bundles/DoctrineFixturesBundle/index.html我还做了一个使用教义迁移的 Zend Framework 项目,你可以在这里找到更多相关信息doctrine-project.org/projects/migrations/2.0/docs/reference/…
    【解决方案2】:

    从文档中不是很清楚,但消息来源说...

    doctrine/dbal/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php:        if (isset($options['auto_increment'])) {
    doctrine/dbal/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php:            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);
    

    so for mysql 作为@table 注释的选项

    * @ORM\Table(name="xxx", options={"auto_increment": 100})
    

    【讨论】:

    【解决方案3】:

    这里是在 MySQL 2 中设置 auto_increment 的完整代码示例:

    $connection = $this->getEntityManager()->getConnection();
    $connection->prepare('ALTER TABLE my_table AUTO_INCREMENT = 100;')->execute();
    

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 2014-10-08
      • 2022-07-21
      • 2014-07-24
      • 1970-01-01
      相关资源
      最近更新 更多