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

查看:248
本文介绍了@UniqueConstraint和@Column(unique = true)选项之间的原则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

CLASS

/**
 * @ORM\Entity
 * @ORM\Table(
 *      name="user",
 *      uniqueConstraints={
 *          @ORM\UniqueConstraint(columns={"email"})
 *      }
 * )
 */
class User
{
    /**
     * @ORM\Column(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

CLASS

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User
{
    /**
     * @ORM\Column(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)选项之间的原则ORM级别差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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