phpdoctrinedoctrine-orm

Is there a way to enforce a unique column using doctrine2?


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(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;
}

Solution

  • 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.