首页 > 解决方案 > Doctrine ORM 中的索引长度

问题描述

我有一个遗留应用程序,其中有一个表,其创建定义如下所示:

CREATE TABLE my_schema.shops_urls (
   id BIGINT UNSIGNED NOT NULL,
   id_shop INT UNSIGNED NOT NULL,
   url VARCHAR(2000) NOT NULL, 
   
   PRIMARY KEY (id, id_shop),
   INDEX url (url),
   INDEX id_shop_url (id_shop, url) 
) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB';

遗留应用程序正在改进并迁移到 Symfony。因此表/实体

/**
 * ShopsUrls
 *
 * @ORM\Entity(repositoryClass=ShopsUrlsRepository::class)
 * @ORM\Table(
 *      name="shops_urls",
 *      schema="my_schema",
 *      indexes={
 *          @ORM\Index(name="url", columns={"url"}),
 *          @ORM\Index(name="id_shop_url", columns={"id_shop","url"})
 *      }
 * )
 */
class ShopsUrls
{
    /**
     * @var int|null
     * 
     * @ORM\Column(name="id", type="bigint", nullable=false, options={"unsigned":true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     */
    private ?int $id;

    /**
     * @var int|null
     * 
     * @ORM\Column(name="id_shop", type="integer", nullable=false, options={"unsigned":true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     */
    private ?int $id_shop;

    /**
     * @var string|null
     * 
     * @ORM\Column(name="url", type="string", length=2000, nullable=false)
     */
    private ?string $url;
}

执行时$ bin/console doctrine:schema:update --force,显示如下错误:

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 3072 bytes

执行上面的 SQL 给出了同样的错误。如果我们按如下方式修改索引,则 SQL 将正确执行(因此如果创建了表)。

   INDEX url (url(100)),
   INDEX id_shop_url (id_shop, url(100))

问题

有没有办法在 Doctrine annonations 中指定索引长度?就像是:

 * @ORM\Table(
 *      name="shops_urls",
 *      schema="my_schema",
 *      indexes={
 *          @ORM\Index(name="url", columns={"url(100)"}),
 *          @ORM\Index(name="id_shop_url", columns={"id_shop","url(100)"})
 *      }
 * )

执行$ bin/console doctrine:schema:update --force,给出以下错误:

There is no column with name 'url(100)' on table 'shops_urls'.

标签: phpdoctrine-ormdoctrine

解决方案


您需要在注释的第三个参数options中指定索引长度。ORM\Index

@ORM\Index(name="url", columns={"url(100)"}, options={"lengths": {100}})

或作为组合索引的列表

@ORM\Index(name="id_shop_url", columns={"id_shop", "url"}, options={"lengths": {10, 100}})

为您想要完全索引的那些字段设置 null

@ORM\Index(name="id_shop_url", columns={"id_shop", "url"}, options={"lengths": {null, 100}})

推荐阅读