'How to give a unique constraint in lucid model, I am using lucid in adonis with typescript
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>
}
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hussain |