如何设置3属性是模型的唯一

时间:2017-06-14 09:10:34

标签: yii2 unique rules

我有一个包含上述属性的模型TblPayroll,我想检查'fk_int_emp_id''fk_int_payroll_month''fk_int_payroll_year'的唯一性。如果这三个字段已经在数据库中,则不应插入。应该插入至少一个是不同的。如何检查唯一性?

public function attributeLabels()
    {
        return [
            'pk_int_payroll_id' => 'Payroll Id',
            'fk_int_emp_id' => 'Employee',
            'vchr_worked_hours' => 'Worked Hours',
            'vchr_actual_hours' => 'Actual Hours',
            'fk_int_payroll_month' => 'Month',
            'fk_int_payroll_year' => 'Year',
        ];
    }

public function rules()
    {
        return [
            [[ 'vchr_worked_hours', 'vchr_actual_hours', 'fk_int_payroll_month', 'fk_int_payroll_year'], 'required'],

            //[['fk_int_emp_id', 'fk_int_payroll_year','vchr_worked_hours','vchr_actual_hours'], 'integer'],
            //[['fk_int_emp_id','fk_int_payroll_month','fk_int_payroll_year'], 'string', 'max' => 50],
            [['fk_int_emp_id'], 'exist', 'skipOnError' => true, 'targetClass' => TblEmployee::className(), 'targetAttribute' => ['fk_int_emp_id' => 'pk_int_emp_id']],
            [['fk_int_payroll_month'], 'exist', 'skipOnError' => true, 'targetClass' => TblPayrollMonth::className(), 'targetAttribute' => ['fk_int_payroll_month' => 'pk_int_payroll_month_id']],
            [['fk_int_payroll_year'], 'exist', 'skipOnError' => true, 'targetClass' => TblPayrollYear::className(), 'targetAttribute' => ['fk_int_payroll_year' => 'pk_int_payroll_year_id']],
        ];
    }

1 个答案:

答案 0 :(得分:0)

试试这个

[['fk_int_emp_id', 'fk_int_payroll_month', 'fk_int_payroll_year'], 'unique', 'targetAttribute' => ['fk_int_emp_id', 'fk_int_payroll_month', 'fk_int_payroll_year'], 'message' => 'The combination of .... has already been taken.'],