有没有办法使用doctrine2强制执行唯一列?

时间:2011-09-03 18:43:29

标签: php doctrine doctrine-orm

我知道我总是可以使用MYSQL架构设置一个唯一的数据库密钥,但是,如果ORM像doctrine一样允许你在代码中设置一个唯一的列,那就好奇了吗?

例如,如何在代码中创建它,以便用户名在运行时在代码中是唯一的?

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(300) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(300) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(300) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;






function insert_user($username,$email,$password) 
        {
$user = new User();
$user->setUsername($username); //HOW CAN I MAKE THIS UNIQUE IN CODE?
$user->setEmail($email);
$user->setPassword($password);

    try {
            //save to database
            $this->em->persist($user);
            $this->em->flush();
        }
        catch(Exception $err){

            die($err->getMessage());

            return false;
        }
        return true;
        }

3 个答案:

答案 0 :(得分:54)

只提供一个更简单的替代解决方案。

如果是单列,您只需在列定义中添加唯一列:

class User
{
   /**
    * @Column(name="username", length=300, unique=true)
    */
   protected $username;
}

关于此的文件: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/annotations-reference.html#annref_column

如果您需要多列的唯一索引,您仍需要使用Andreas提供的方法。

注意:我不确定自哪个版本可用。可能这在2011年尚未推出。

答案 1 :(得分:22)

我假设这是你想要的?

<?php
/**
 * @Entity
 * @Table(name="ecommerce_products",uniqueConstraints={@UniqueConstraint(name="search_idx", columns={"name", "email"})})
 */
class ECommerceProduct
{
}

http://www.doctrine-project.org/docs/orm/2.0/en/reference/annotations-reference.html#annref-uniqueconstraint

由于我没有你的代码,我无法给你一个实际的例子。

答案 2 :(得分:2)

您必须在 @Table 声明

中设置uniq约束
  

<强> @UniqueConstraint

     

在实体类的@Table注释中使用注释   水平。它允许提示SchemaTool生成唯一的数据库   对指定表列的约束。它只有意义   SchemaTool模式生成上下文。

     

必需属性:    name :索引的名称,    columns :列数组。

<?php
/**
 * @Entity
 * @Table(name="user",uniqueConstraints={@UniqueConstraint(name="username_uniq", columns={"username"})})
 */
class User
{
   /**
    * @Column(name="username", length=300)
    */
   protected $username;
}

来源:http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/reference/annotations-reference.html#annref-uniqueconstraint

相关问题