I know I can always set a unique DB key using MYSQL schema however was just curious if ORM's like doctrine allowed you to set a column to be unique in code?
For example how can I make it in code so that username's are unique in code at run time?
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(300) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(开发者_Go百科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 ;
<?php
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;
}
Just providing an alternate solution that is a little simpler.
If it is a single column, you could simply add a unique on the column definition:
class User
{
/**
* @Column(name="username", length=300, unique=true)
*/
protected $username;
}
Documentation on this: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/annotations-reference.html#annref_column
If you need a unique index on multiple columns, you still need to use the method Andreas provided.
note: I'm not sure since which version this is available. It might be this was not yet available in 2011.
I'm assuming this is what you want?
<?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
Since I don't have your code I can't give you a practical example.
You have to set the uniq constraints in the @Table declaration
@UniqueConstraint
Annotation is used inside the @Table annotation on the entity-class level. It allows to hint the SchemaTool to generate a database unique constraint on the specified table columns. It only has meaning in the SchemaTool schema generation context.
Required attributes: name: Name of the Index, columns: Array of columns.
<?php
/**
* @Entity
* @Table(name="user",uniqueConstraints={@UniqueConstraint(name="username_uniq", columns={"username"})})
*/
class User
{
/**
* @Column(name="username", length=300)
*/
protected $username;
}
source: http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/reference/annotations-reference.html#annref-uniqueconstraint
精彩评论