【发布时间】:2015-06-10 12:12:46
【问题描述】:
我有一个用户类如下:
/**
* User
*
* @ORM\Table()
* @ORM\Entity
* @UniqueEntity("username")
*/
class User implements UserInterface
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="username", type="string", length=30, unique=true)
*/
private $username;
...
如您所料,我想保持用户名的唯一性。当我尝试注册一个与以前的用户名重复的新用户时,我得到一个 db 异常:
An exception occurred while executing 'INSERT INTO User (username, hashedpassword, email) VALUES (?, ?, ?)' with params ["xx", "$2y$10$7rrY0tw0eG8ui7hRkpGI..8Wf16DP1fQMLymaOmHnbZsBw6M1uY.i", "ddsds@u.com"]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'xx' for key 'UNIQ_2DA17977F85E0677'
我认为问题可能出在我的注册控制器上。我正在使用
上给出的那个http://symfony.com/doc/current/cookbook/doctrine/registration_form.html
相关位:
class AccountController extends Controller
{
public function registerAction()
{
$registration = new Registration();
$form = $this->createForm(new RegistrationType(), $registration, array(
'action' => $this->generateUrl('account_create'),
));
return $this->render(
'RezialRezialBundle:Account:register.html.twig',
array('form' => $form->createView())
);
}
public function createAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(new RegistrationType(), new Registration());
$form->handleRequest($request);
if ($form->isValid()) {
$registration = $form->getData();
//should I manually check for unicity here?
$em->persist($registration->getUser());
$em->flush();
//The following 3 lines make the user automatically login
//upon successfull registration!
$user = $registration->getUser();
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.token_storage')->setToken($token);
return $this->redirectToRoute('homepage');
}
return $this->render(
'RezialRezialBundle:Account:register.html.twig',
array('form' => $form->createView())
);
}
}
关于缺少什么的任何想法?
【问题讨论】:
标签: php symfony unique-constraint