How to check if value is unique from inside model?

Hi, generating a random alpha-numeric code in a model before a save. Before the save occurs though I’d like to check the database to make sure the code is unique. Can I use the rules or do I need to do it another way?

This doesn’t work. What am I doing wrong?

In model:

function beforesave():

  $this->code = randomCode();

function randomCode(){



    	generate code

     } while(!Model::model()->exists('code=:code',array(':code'=>$code)));

  return $code;


Can you use the CUniqueValidator? Described here:

Not sure if that will work, because I don’t want it to throw an error, just to rerun the random generator.

You probably need to remove the ! from your while condition, otherwhise you say: Create new code as long as it does not exist in DB.

While i once shared your approach, i’m not sure anymore if it’s really necessary. E.g. just think about how many different hashes are possible with a 32 Byte md5() alone. Even with not very good randomness i believe it will never happen in our lifetimes that you create the same code again (probably not even in the lifetime of the universe…). If you apply a UNIQUE index on your DB, you’ll be save that even in the very very very (…) very seldom case of a duplicate hash, it will not go into your DB.

It’s only a 8 character hash, but I took your advice and moved it out of the while. Made it equal to a variable and used that in the while loop. It works just fine now. thanks.