Good day!
There is a table with a unique index on two fields at once:
CREATE TABLE table_name( id INT(11) NOT NULL AUTO_INCREMENT, id_field INT(11) NOT NULL, title VARCHAR(255) NOT NULL, PRIMARY KEY (id), INDEX id_field (id_field), UNIQUE INDEX title (title, id_field) -- индекс );
As in CActiveRecord::rules()
for the title
field, create a unique
rule so that uniqueness is checked on the entire table, but, exactly, within the limits of the id_field
value?
UPD: Working code
// Controller public function actionAction( $id_field,$id_item=null ) { // ... $item=null; if( $id_item!==null ) $item=FieldItem::model()->findByPk($id_item); if( $item===null ) $item=new FieldItem(); if( isset($_POST['FieldItem']) ) { $item->attributes=$_POST['FieldItem']; $item->id_field=$id_field; if( $item->save() ) $this->redirect(/*...*/); } // ... } // FieldItem public function rules() { return array( //... array('title', 'uniqueTitle'), //... ); } public function uniqueTitle( $attribute,$params=array() ) { if( !$this->hasErrors() ) { $params['criteria']=array( 'condition'=>'id_field=:id_field', 'params'=>array(':id_field'=>$this->id_field), ); $validator=CValidator::createValidator('unique',$this,$attribute,$params); $validator->validate($this,array($attribute)); } }
id_field
andtitle
should beid_field
- KiTE