简体   繁体   中英

Yii2 Model Unique Rules for combination of more than one attribute

How can I specify a unique rule in my models for a combination of more that one attributes? I want a rule that can't allow insert of a record with a combination of the same FIELD100 , FIELD3

return [
    [['FEETYPE_F_V_R_','FIELD32','IS_CUSTOMER_EXPENSE','IS_BANK_EXPENSE','IS_BANK_EXPENSE','FIELD100'], 'required'],
    [['ID', 'ACTIVE', 'APPROVED', 'REWORKED', 'IS_CUSTOMER_EXPENSE', 'IS_BANK_EXPENSE', 'IS_BANK_EXPENSE'], 'integer'],
    [['AMOUNT'], 'number'],
    [['REWORKEDON'], 'safe'],
    [['FIELD3', 'FIELD32'], 'string', 'max' => 10],
    [['FEETYPE_F_V_R_', 'FIELD24'], 'string', 'max' => 2],
    [['FIELD100', 'CREATEDBY', 'APPROVEDBY', 'REWORKEDBY'], 'string', 'max' => 50],
    [['CREATEDDATE', 'APPROVEDDATE'], 'string', 'max' => 7],
    [['MEMOCODE'], 'string', 'max' => 20],
    [['ID'], 'unique'],
];

You can use CompareValidator in your Model.

public function rules()
{
    return [ 
        [
            'FIELD100',
            'compare',
            'compareAttribute' => 'FIELD3',
            'operator' => '!=',
            'message' => 'Both values can not be the same'
        ]
    ];
}

For more info see the docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM