@UniqueConstraint 和 @Column(unique=true) 选项之间的 Doctrine ORM 级别差异 [英] Doctrine ORM level difference between @UniqueConstraint and @Column(unique=true) options

查看:18
本文介绍了@UniqueConstraint 和 @Column(unique=true) 选项之间的 Doctrine ORM 级别差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数据库级别,使用一个而不是另一个选项来定义 UNIQUENESS 时没有区别,如下所示.虽然 @UniqueConstraint 在其文档中读到它仅在 SchemaTool 模式生成上下文中有意义",但两者之间是否存在 ORM 级别差异?我的意思是当我们运行查询时,事情的处理方式是否不同?

In database level, there is no difference when using one over another option for defining UNIQUENESS as shown below. Although @UniqueConstraint reads in its documentation "It only has meaning in the SchemaTool schema generation context", is there a ORM level difference in between? I mean when we run queries, do things get handled differently?

  • @UniqueConstraint
  • @Column (unique=true)

示例 - @UniqueConstraint

/**
 * @ORMEntity
 * @ORMTable(
 *      name="user",
 *      uniqueConstraints={
 *          @ORMUniqueConstraint(columns={"email"})
 *      }
 * )
 */
class User
{
    /**
     * @ORMColumn(name="email", type="string", length=100)
     */
    private $email;
}

DQL

CREATE TABLE `user` (
  `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  UNIQUE KEY `UNIQ_8D93D649E7927C74` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

示例 - @Column - unique=true

/**
 * @ORMEntity
 * @ORMTable(name="user")
 */
class User
{
    /**
     * @ORMColumn(name="email", type="string", length=100, unique=true)
     */
    private $email;
}

DQL

CREATE TABLE `user` (
  `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  UNIQUE KEY `UNIQ_8D93D649E7927C74` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

推荐答案

基本没有区别.两者都在列上创建唯一键.

There is basically no difference. Both create a unique key on a column.

但是 @UniqueConstraint 有更多的可能性.使用 @UniqueConstraint 您可以为键命名或跨越多个列.缺点是要键入更多内容(没有那么糟糕),并且列名必须是数据库中的列名,而不是 php 属性名.

But @UniqueConstraint has much more possibilities. With @UniqueConstraint you can give the key a name or span over multiple columns. The downside is much more to type (not as worse) and the column names must be the column names in the database, not the php property name.

unique=true 是在单个列上创建唯一键的最简单方法.

unique=true on the @Column is the simplest way of creating unique keys on a single column.

在运行查询时,没有区别.ORM 不关心唯一定义.特别是在插入时,您会从数据库中获得关于唯一性违规的崩溃,而不是来自 ORM.您必须自己确保唯一性,例如使用 Symfony 中的唯一实体验证.

While running queries, there is no difference. The ORM doesn't care about unique definitions. Especially on inserts you get a crash from the database about uniqueness violation and not from the ORM. You have to ensure the uniqueness on your own, for example with the unique entity validation in Symfony.

这篇关于@UniqueConstraint 和 @Column(unique=true) 选项之间的 Doctrine ORM 级别差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆