Indicative: There's a validate that verify the unique of more than 1 column as the same time?

In my table i have a unique constraint of two columns:

table.unique(['class_id', 'book_id'])

There’s a way to make a validate that check if this two columns is unique when i’m putting some data in the table?

Nowadays i use something like:

const rules = () => ({

 class_id: 'required',
})

const messages = {
 unique: field => `${field} must be unique`,
}

and in my store function:

const validation = await validate(values, rules(values), messages)

    if (validation.fails()) {

      return response.validateError(validation)

    }
2 Likes

Hi @veronesecoms. You coul try make your code like this:

const rules = () => ({
 class_id: 'required|unique:table',
 book_id: 'required|unique:table'
})

const messages = {
 unique: field => `${field} must be unique`,
}

Hi, i need to check as a set"class_id" and “book_id” is unique.

I need the validation like i defined in the migration:

table.unique(['class_id', 'book_id'])

Hi @veronesecoms!

Seems like @willvincent has written blog post exactly on that topic: https://willvincent.com/2018/07/17/validating-compound-field-uniqueness-in-adonisjs/

Thank you for that @willvincent!

3 Likes

Yep, I’ve been using the uniqueCompound validation rule that I wrote about in the blog post linked above in production for almost a year. Works great :slight_smile:

2 Likes