YiiHaa Webdevelopment blog about Yii-framework and more


Validate unique constraints with more then one attribute

Yii comes with bucket of validators including a unique validator which validates whether an attribute value is unique in the corresponding database table. But what if your database unique constraint contains more than one attribute?

I have seen a couple Yii extensions which solve the problem but none of them are using the built-in CUniqueValidator parts. There are two ways to solve the validation problem, the first one is to add some criteria to the unique validator:

public function rules() {
	return array(
		array('firstKey', 'unique', 'criteria'=>array(

That will do the trick, however it can get a bit cleaner. The UniqueAttributesValidator does this for you:

public function rules() {
	return array(
		array('firstKey', 'UniqueAttributesValidator', 'with'=>'secondKey'),

The UniqueAttributesValidator uses parts of CUniqueValidator and extends it by adding certain criteria. It also works for unique constraints with N attributes:

public function rules() {
	return array(
		array('firstKey', 'UniqueAttributesValidator',

Download the UniqueAttributesValidator HERE.

Posted by martijn

Comments (16) Trackbacks (0)
  1. “more thEn” ?

  2. Der UniqueAttributesValidator funktioniert sehr gut. Der Code sieht auch sauber aus.

    Allerdings musst du das Beispiel oben nochmal überarbeiten:
    * Der Zugriff auf die Model-Eigenschaften ist mit $this nicht möglich, da der Wert noch nicht gesetzt ist.
    * Der Zugriff funktionierte bei mir aber so $_POST['Model']['secondKey']

    Da diese Schreibweise nicht sehr schön ist bevorzuge ich auch deinen Validator.


  3. The UniqueAttributesValidator works very well. The code looks clean.

    However, you have the example revise up again:
    * Access to the model properties using $ this is not possible, because the value is not yet set.
    * Access work for me but that $ _POST ['Model'] ['secondkey']

    Since this notation is not very nice I prefer your validator.


  4. Nice and clean solution, but I suggest changing line 27 to:

    $conditionParams[] = $object->getTableAlias(true) . ‘.’ . “`{$attribute}`=:{$attribute}”;

    Otherwise you’re bound to get errors if the model has any eager relations (“with”) set in the default scope.

  5. Hi,

    Thanks for this simple and great extension! I noticed a bug, I’m using SQL Server instead of MySQL and notation of columns with `COLUMN NAME` is not supported on SQL Server and raises exception. It would work in both databases simply removing character ` from code, so it would be:

    $conditionParams[] = “`{$attribute}`=:{$attribute}”;
    $conditionParams[] = “{$attribute}=:{$attribute}”;


  6. Absoluter netter Blog. Werde jetzt öfter reinschauen Vielen Dank und Grüsse aus Köln

  7. Great piece of code. Thanks!

  8. How to install this? I downloaded it, unzipped it in “extensions” folder and added the file path in “components” in config/main.php but can not make it to work.

  9. Problem with Gii
    Hey, im getting this exception when i try to use Gii – models,

    UniqueAttributesValidator and its behaviors do not have a method or closure named “init”.

  10. Hai thanks for the good extension, but it is not working for me.,please tell me where to install your extension.,now am installed it on \protected\extension\
    and using it like the following lines,

  11. Great code! Thanks.

  12. But yeah Many thanks for taking the time to argue this, I feel strongly about it and in truth like learning more on this topic. If doable, as you gain expertise, would you mind updating your site with more information? It is extremely helpful for me.
    Ray Ban Wayfarer Original Replica http://www.mcevoyandfarmer-pathology.com/wp-hebav.php?pid=Ray-Ban-Wayfarer-Original-Replica

  13. I had this article bookmarked some time in the past but my notebook crashed. I have since gotten a new one and it took me a while to find this! I also in fact like the theme though.
    cheap beats by dr dre studio http://www.makingfriendswiththedark.com/wp-share.php?pid=cheap-beats-by-dr-dre-studio

  14. When you are looking for UGG Boots, you will have plenty of styles to choose from. There are ankle length boots for those short excursions, and shin and knee high boots for the times in which you plan on being out in the cold for much longer.
    Botas Ugg http://www.avesibericas.es/avesibericas.asp

  15. et along with dark sun-brushed face and also costs three hundred dollars? 50. The last the first is a great deal less costly, for this is made of stainless circumstance along with necklace using darkish sun-brushed switch. Its at? 92. Currently, Gucci provides bec.

  16. a new mini-skirt. If you’d prefer the planning associated with gladiator penis pumps however you may need a tiny dressier overall appeal, grab this Mairin sends with regard to $237. 00. Most of these 5′ program high heel sandals are usually gorgeous all of which will exhibit of which extraordinary pedicure.

Leave a comment

No trackbacks yet.