Yii Framework Forum: model rule for composite primary key - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

model rule for composite primary key Rate Topic: -----

#1 User is offline   rahul.vit09 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 48
  • Joined: 07-February 11

Posted 12 February 2011 - 12:06 AM

hello everyone as i know Gii will not be used to generated CRUD for composite primary key database.

So is there any option to create rule so that we can match uniqueness of two or more fields of database.

for example i am having three fields category, userid, and email.

i want to check if category and userid is unique. and category and email is unique.
0

#2 User is offline   rahul.vit09 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 48
  • Joined: 07-February 11

Posted 12 February 2011 - 01:47 AM

finally i got a perfect solution to this problem. It has been a serious issue around this forum.

thank to ololo for this.

http://www.yiiframework.com/forum/.......composite-unique-key-validation/page__gopid__80509#entry80509
0

#3 User is offline   Pep 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 22
  • Joined: 06-August 11

Posted 21 April 2012 - 03:42 AM

Here is an example for you. In my opinion, the built in CUniqueValidator is more than enough to handle this task. It is very flexible and you can even use relations to verify the uniqueness of an attribute. The default error message is appropriate but you can customize it to taste.

For example, an application can have many users and each user can have their own invoice numbers. However, you want the users not to use duplicate invoice numbers from their own account. In this example the unique composite key would consist of the "invoice_number" attribute and the "user_id" attribute through the relation "account". (You could of course have the user_id attribute in the invoice model but I wanted to demonstrate the use of relations along with the use of validating unique composite keys.) Your rule in the invoice model could look like this:

/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
	// NOTE: you should only define rules for those attributes that
	// will receive user inputs.
	return array(
                array('invoice_number', 'unique', 'caseSensitive'=>false, 'criteria'=>array(
                                'condition'=>'account.user_id = :id',
				'params'=>array(':id'=>Yii::app()->user->id),
				'with'=>'account',
			),
			'message'=>'{attribute} "{value}" is already in use.'),
	);
}

1

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users