3

In adonis.js i am trying to add a unique constraint to email field just like we do it in sequelize,prismajs or any other orm.Is it posible to add in adonis.

    import { DateTime } from 'luxon'
    import { BaseModel, column, computed, HasMany, hasMany } from '@ioc:Adonis/Lucid/Orm'
    import Post from 'App/Models/Post'
    
    export default class User extends BaseModel {
      @column({ isPrimary: true })
      public id: number
    
      @column()
      public firstName: string
    
      @column()
      public lastName: string
    
      @column()
      public email: string
    
      @column({ serializeAs: null })
      public password: string
    
      @column.dateTime({ autoCreate: true })
      public createdAt: DateTime
    
      @column.dateTime({ autoCreate: true, autoUpdate: true })
      public updatedAt: DateTime
    
      @computed()
      public get fullName() {
        return `${this.firstName} ${this.lastName}`
      }
      @hasMany(() => Post, {
        foreignKey: 'userId',
      })
      public posts: HasMany<typeof Post>
    }
Mradul Jain
  • 62
  • 12

1 Answers1

0

I am assuming that you would want to validate whether the email address is unique before creating the user in the database. In that case you can use the unique validation to ensure that the email entered by the user does not exist in the database.

import { schema, rules } from '@ioc:Adonis/Core/Validator'
{
  email: schema.string({}, [
    rules.unique({ table: 'users', column: 'email' })
  ])
}

You can learn more about Validator and Unique Rule Validation in official Adonis Documentation.

Hussain
  • 71
  • 4