jin*_*ini 13 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;
}
Run Code Online (Sandbox Code Playgroud)
Dop*_*yNL 61
只是提供一个更简单的替代解决方案.
如果它是单个列,您只需在列定义上添加唯一:
class User
{
/**
* @Column(name="username", length=300, unique=true)
*/
protected $username;
}
Run Code Online (Sandbox Code Playgroud)
有关此文档:https: //www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/annotations-reference.html#annref_column
如果您需要多列的唯一索引,则仍需要使用Andreas提供的方法.
注意:我不确定自哪个版本可用.这可能是2011年尚未提供的.
And*_*eas 22
我假设这是你想要的?
<?php
/**
* @Entity
* @Table(name="ecommerce_products",uniqueConstraints={@UniqueConstraint(name="search_idx", columns={"name", "email"})})
*/
class ECommerceProduct
{
}
Run Code Online (Sandbox Code Playgroud)
由于我没有你的代码,我不能给你一个实际的例子.
| 归档时间: |
|
| 查看次数: |
16984 次 |
| 最近记录: |