CRUD #2714
Vishwas-verma
started this conversation in
General
CRUD
#2714
Replies: 1 comment
-
I don't know what you mean with perfect, cause you can have a bunch of different situations. Regardless, let's imagine you want to create a Contact CRUD with only import { column, BaseModel } from '@ioc:Adonis/Lucid/Orm'
export default class Contact extends BaseModel {
public static table = 'CONTACT'
@column({ isPrimary: true, columnName: 'id' })
public id: number
@column({ columnName: 'name' })
public name: string
} Remember that this is a opinionated framework, so you can use those opinions for your table name/column names. Route.resource('contacts', 'ContactController').apiOnly() // apiOnly for spa's Now you need a controller and a validator import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Contact from './Contact'
import ContactValidator from './ContactValidator';
export default class ContactController {
async index({ request }: HttpContextContract) {
const { page = 1, limit = 10} = request.all()
return await Contact.query().paginate(page, limit);
}
async store({ request }: HttpContextContract) {
const entity = await request.validate(ContactValidator);
return await Contact.create(entity);
}
async show({ params }: HttpContextContract) {
return Contact.find(params.id)
}
async update({ request, params }: HttpContextContract) {
const entityUpdated = await request.validate(ContactValidator);
let entity = await Contact.findOrFail(params.id)
entity.merge(entityUpdated)
return await entity.save();
}
async destroy({ params }: HttpContextContract) {
const entity = await Contact.findOrFail(params.id)
return await entity.delete()
}
} import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { schema } from '@ioc:Adonis/Core/Validator'
export default class ContactValidator {
constructor(private ctx: HttpContextContract) { }
schema = schema.create({
name: schema.string(),
})
cacheKey = this.ctx.routeKey
messages = {}
} I think that's it ....remember that everything i posted here you can find in the docs |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hey geeks after seing lots of documentation and code can anybody know ,how to write perfect CRUD apis using Model method like (create,all,find)?
Also the perfect way to do operations with relationship model ?
Recommended Adonis V5.
Beta Was this translation helpful? Give feedback.
All reactions