Search code examples
yii2yii2-modelyii2-validation

Yii2 : how to check value is unique with below scenario


my table and its data

id   |type | email
1    |1    | user1@domain.com
2    |1    | user2@domain.com
3    |2    | user3@domain.com
4    |2    | user4@domain.com
5    |2    | user5@domain.com

Their is lots of type 1,2,3,4,5,..

All TYPE has dublicate emails except type 2

but,I want to make column email unique only for type 2 using yii2 model validation


Solution

  • You can use filter and try something like this, not tested though

    ['email', 'unique', 'targetClass' => Model::className(), 'filter' => function ($query) {
        return $query->andWhere(['type' => 2]);
    }],