Using an existing table with Adonisjs

Asked

Viewed 128 times

0

I am a beginner with the Adonisjs framework and need to use it in an existing table with data. Researching I found that I should create a Model for the table, but it didn’t work and I couldn’t find a way to work. I have a similar scenario to below: A table called empresas_clientes in a Postgres bank with the following structure:

create table empresas_clientes(
    codigo serial not null primary key,
    razao varchar(50) not null
);

And I created a model called Cliente with the command adonis make:model cliente with the following structure:

'use strict'

/** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */
const Model = use('Model')

class Cliente extends Model {

    static get table() {
        return 'empresas_clientes'
    }

    static get primaryKey() {
        return 'codigo'
    }

    static get createdAtColumn() {
        return null
    }

    static get updatedAtColumn() {
        return null
    }
}

module.exports = Cliente

I also have the controller:

'use strict'

const Cliente = require('../../Models/Cliente')

class ClienteController {

    async index({ request }) {
        const cliente = await Cliente.first()
        return cliente
    }
}

module.exports = ClienteController

And the following route:

Route.get('/clientes', 'ClienteController.index')

But when access /clientes I get an error message inserir a descrição da imagem aqui

I could not solve this problem to and make the route return the JSON of the clients, I believe it is some problem due to being using an existing table.

  • What version of Adonisjs?

  • It is version 4.1.0

1 answer

1

Your code is almost right, you just need to fix one thing, in your controller in the Index function you are calling First wrong the right way would be:

Const cliente = await Cliente.query().first()

And you can remove these static methods that you’ve mounted inside the model leaves it the same as it was when you created it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.