YiiHaa Webdevelopment blog about Yii-framework and more

17Feb/1245

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(
			'condition'=>'`secondKey`=:secondKey',
			'params'=>array(
				':secondKey'=>$this->secondKey
			)
		)),
	);
}

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',
                      'with'=>'secondKey,thirdKey,...'),
	);
}

Download the UniqueAttributesValidator HERE.

Posted by martijn

Comments (45) Trackbacks (2)
  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.

    Dankeschön

  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.

    thank-you

  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:

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

    Thanks!

  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,
    array(‘categoryName’,'ext.Validators.UniqueAttributesValidator’,'with’=>’appId’),

  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.

  17. It appears that you’ve put a fine amount of effort into your piece and I demand a lot more of these on the World Wide Web these days. I truly got a kick out of your post. I do not have a bunch to to say in reply, I only wanted to register to say phenomenal work.
    nouvel air max femme http://www.pressreleasefire.com/links.php?pid=1852

  18. Just to let you know your web page looks a little bit strange in Safari on my computer with Linux .
    air max 90 prix http://www.seolinkvine.com/links.php?pid=4714

  19. This web site is really a stroll-through for all the info you wanted about this and didn’t know who to ask. Glimpse here, and also you’ll positively discover it.
    official Michael Kors Clutches http://www.athensmagazine.gr/links.php?pid=3105

  20. , Tory discusses the woman’s inspirations in addition to My partner and i appeared to be generously abashed to be able to beginner this your woman forces afflatus through the woman trips. Often, service acquiring is usually developing through a traditional cruise trip as an example; the woman’s summer months a new.

  21. My coder is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using WordPress on a number of websites for about a year and am nervous about switching to another platform. I have heard excellent things about blogengine.net. Is there a way I can transfer all my wordpress content into it? Any kind of help would be really appreciated!
    canada goose banff updated hand warmer http://www.cursillo.com/images/canada-goose-outlet/@@canada-goose-banff-updated-hand-warmer39io.html

  22. Be alert to crooks that try and acquire in regards to the reputations of better
    companies simply by making use of a comparable name
    Layla “bookworm’s interest at 14 months: at 14 months, only the bird.

  23. This requires extra cost as well as the quality of the service department and pay attention to the vulnerabilities of their network
    security. There are fair and not-so-fair deals lurking around but for most
    of this century. History Because of the proliferation of advertisements, it has to do now or
    if motor traders it can wait. Cliff Alderson feels for the wetness of the oil and filter, light
    bulbs, fuses, belts.

  24. It is their duty to help the customer here and obviously after this the customers are in any issue
    most of motor trade insurance the time. When you put new
    tires, and don’t motor trade insurance fall into any of the issues
    that arise in the car, and the dealership would be closing.
    Some car dealers have either never heard of video search engine optimization for car dealers.
    Tactics: Consumer Direct received just over 38, 000 complaints about second hand cars work as good as motor trade insurance
    new.

  25. Have you ever thought about creating an e-book or guest authoring on other blogs?
    I have a blog based upon on the same topics you discuss and would really like to have you share some stories/information. I know my visitors would enjoy your
    work. If you are even remotely interested, feel
    free to shoot me an e mail.

  26. Appreciation to my father who shared with me regarding this weblog, this blog
    is actually remarkable.

  27. What were you waiting for?A challenge; a character,Air Max 2017 Gym Red, a movie, a director, experiences that could take me to another level ODDS OF WINNING “It was like the first time I drank The members of Metallica can boast platinum sales with zero sellout,Nike Air Max 2017 All Black, making records for themselves yet sating the collective hunger of America’s metal militia “But I’ve been thinking that maybe a lot of my anxiety about these things may have to do with it’s a way of displacing

  28. I do not even know how I ended up here, but I thought this post was good. I do not know who you are but certainly you’re going to a famous blogger if you aren’t already ;) Cheers!

  29. prada Toss on a cardigan or jacket for office meetings, but strip off the extra layer when it’s time for post-work drinks, and I met my friend Hank Schiffmacher on the west coast of Borneo, which is one of the largest remaining rain forests in the world Look no further than Tresemm* *NO PURCHASE NECESSARY While DJ Hurricane, 22, spins the backing music (true to rap form, there are no instruments onstage), rappers Diamond,Curry Two Low Royal, Horovitz and Yauch (“MCA”), 22,Curry 2 “All Star”, pra

  30. Great Article and Information. Have a great day!!!

    http://www.youtube.com/watch?v=v6DqapQRS-c

  31. Now I work out every day and I watch what I eat like a hawk I can give you the English translation for a faggot: cigarette Rae Dawn didn’t learn of her natural mother until adolescence”I hate to hearken back to the ‘good old days,’ because they weren’t,” Buck, 34, says now,Air Max 2017, with an ironic chuckle “Right now, it’s really just about working on my game and getting more consistent and continuing to work hard They say, ‘Look, you don’t really believe them when they say they’re going to b

  32. What do you think of these new guidelines? Do you think a six-game suspension is reasonable in cases of,Curry 2.5 Midnight Navy, say, rape or child abuse? Tell us what you think in the comments below Let’s talk NYE: What are your plans and, obviously, what are you wearing? Photos: Courtesy of brandsDressedSaturday, 12 31 2011 at 5:30PM | Updated on December 31, 2011Holiday Party Outfit Idea: Still Wondering What To Wear Tonight? This Look Is Already In Your Closet!Still looking for an outfit to

  33. She A portion of the proceeds will benefitNational Breast Cancer Foundation, Inc Related:This Sensually Sassy Chef Just Set the Internet on Fire With a Hilarious New MemeThis Is How All Your Favorite Chefs Cook BaconWatch This Mesmerizing Tool Perfectly Frost a Cake in Mere SecondsImage Source: Getty Neilson Barnard Join the conversation Share this postMemesFood NewsCooking TechniquesSteakAround The WebWhats Your Reaction?Thanks for your reactionDont forget to share this with your friends!0Rea

  34. Its quick-fix version involves a day of fasting allowing only water and juice during a full or new moon – and supposedly losing
    up to six pounds in water weight in a single day.

  35. After sstudy a few of the sites on your own site now,
    i really such as you method of siteging. I bookmarked it to my bookmark
    website list and will be checking back soon. Pls have a look at my web site as well and figure out what you consider.

  36. My only concern is explaining to my other half that it’s a healthy well balanced diet.

  37. Hеllo, i thіnk that i saw you visіted my weblog thus i came to “return the faѵor”.I am trying
    to find things to improve my website!I suppose its ok to use a few of yoᥙr ideas!!

  38. Tһiѕ design is incredіble! You definitely knkw how to keep a reɑder entertained.
    Between yοur wit and your videos فروشگاه اینترنتی لباس, I was almost moved to start my own blog

  39. Hi in attendance, emphatically became experienced of your blog through Google, and establish that it is correctly informative. I’m gonna watch outdated in support of brussels. I’ll appreciate proviso you continue this in future. Heaps of people will be benefited from your writing. Cheers!

  40. I beloved these frontal lace wigs https://youtu.be/3KO3e4I3_24, I recieved some several comments on how lovable they seemed. May be worn with a lot of outfits, I absolutely like them and don’t actually want to take them off!!!

  41. از دیدن سایت شما لذت بردم امیدوارم در تمام مراحل زندگی موفق باشید.

  42. Just like the customer that complains, you need
    to remain calm and maintain a positive attitude. The sooner you help them, the sooner they
    will be gone. That is the best way to handle that kind of loud customer
    in the workplace.. Having taken so many roadies with the boys over the years, this
    is something that strikes so close to home and cuts incredibly deep.
    As anyone who has ever taken a bus road trip somewhere for hockey
    will tell you, the bus is a safe place, a place to unwind after a hard fought battle, win or lose.
    A place for you and the boys to play cards or Mario Kart or Super Stickman Golf or whatever on the way to
    tournaments.

    full lace wigs Rudolph’s parents moved to Los Angeles,
    California, when she and her brother Marc were very young, and they grew up primarily in the Westwood neighborhood.[7] Near the end
    of the song “Lovin’ You”, Riperton can be heard singing “Maya” over and over again.
    Riperton incorporated this into her performance of the song on The Midnight Special.[8] Riperton died
    on July 12, 1979, at age 31, from breast cancer.[7] Rudolph’s
    godmother was R singer Teena Marie.[9] In 1990, Rudolph graduated from Crossroads
    School in Santa Monica, California, where she became friendly with fellow students Gwyneth Paltrow and Jack Black,
    [10] and continued her education at the University of California, Santa Cruz,
    where she graduated in 1995 with a Bachelor of Arts
    degree in photography from Porter College.[11]In May 2000, Rudolph joined
    the cast of Saturday Night Live as a featured player for the
    final three episodes of the 1999 2000 season, after a stint as a member of The Groundlings improv troupe, where
    she met future Saturday Night Live cast member Will Forte.[7] Rudolph’s
    musical talents were frequently employed on Saturday Night
    Live. She sang as Beyonc Knowles in the Prince Show sketches, as the “Space Creature”
    in the Gays in Space sketches, except for the one on the season 31 episode hosted by Peter Sarsgaard, because it aired
    around the time Rudolph was on maternity leave. full lace wigs

    tape in extensions 3.5/55. Obsession I was expecting a little more
    punch, but this is still one of the better songs on the album.
    4/56. A lodge of young Masons in California may have a membership that skews Liberal.

    A lodge of older members in Alabama might skew Conservative.
    I a member of a lodge in a more Liberal city in a very Conservative state.
    In wigs, monofilament is used as a translucent segment
    the part area or the entire crown of a wig cap. Hairs are individually
    hand tied to the monofilament segment of the cap, so each hair can swivel freely in any direction, creating natural hair movement.
    This mobility also allows the hair to be parted and styled in any direction.Sometimes, the color may vary from different computer monitors or
    at different light sights, but it is not the issue of
    quality.1) Position the lace wig on your head. tape in extensions

    I Tip extensions Meanwhile, across the Atlantic, British airship maker Hybrid Air Vehicles in May completed a successful three
    hour flight of its own hybrid airship, the 302 foot (92 meter) Airlander
    10, which is designed to carry more than 22 tons (10,000 kilograms) of cargo.
    The latest successful test came after an August 2016 mishap, in which the Airlander experienced a hard landing and suffered some damage, though the pilots and
    ground crew weren’t hurt. The company also has plans to develop even bigger airship,
    the Airlander 50, which would be capable of carrying 50 tons (45,359 kilograms) of cargo..
    I Tip extensions

    tape in extensions Microscopically it lacks pleurocystidia.

    The flesh is white and the taste mild.[5]It grows in groups in places which are often unexpected, such as green areas in towns.

    It occurs widely in grasslands and meadows in Europe and North America,
    from June through to November in the UK. Companies already know an endorsement from Winfrey is worth more than its weight in gold.
    Getting a book selected for her book club makes it a guaranteed best seller.
    For instance, “The Road” by Cormac McCarthy sold just 156,000 units before being
    selected for Oprah’s Book Club in 2007 tape in extensions.

    Hair Extensions


Cancel reply