How to popular data from another table when a new user is created in Adonisjs

Asked

Viewed 33 times

1

I am starting in Adonisjs and came across the following scenario:

I have a table of user_config that is populated from the creation of a new user.

Doubt: I would like to know first how to do so that after the creation of the user, is also created a record in the table of user_config linked to User.

1 answer

0


I was able to solve it this way:

First we need to have the relationship having the user FK in the user_config record.

class ConfigurationsSchema extends Schema {
  up() {
    this.create("configurations", table => {
      table.increments();

      table
        .integer("user_id") <------ AQUI
        .unsigned()
        .references("id")
        .inTable("users") <------ VINDO DAQUI
        .onUpdate("CASCADE")
        .onDelete("CASCADE")
        .notNullable();

      table
        .integer("expiration_document")
        .notNullable()
        .defaultTo(3);
      table
        .string("date_unit")
        .notNullable()
        .defaultTo("meses");
      table
        .date("warning_expiration")
        .defaultTo("01/01/2023")
        .notNullable();
      table
        .date("warning_expiration_sended")
        .defaultTo("01/01/2023")
        .notNullable();
      table.timestamps();
    });
  }

  down() {
    this.drop("configurations");
  }
}

module.exports = ConfigurationsSchema;

Then we need to inform the relationship between the entities in the models:

Within the Usermodel class:

  configuration() {
    return this.hasOne("App/Models/Configuration");
  }

Within the Configmodel class:

  user() {
    return this.belongsTo("App/Models/User");
  }

Then we need to define in Usercontroller how the store method will work:

     async store({ request, response }) {
    //Buscamos os campos do corpo da nossa requisição e os armazenamos em um objeto chamado data;

    const data = request.all();

    //Criamos um novo usuário repassando os parâmetros vindos da requisição e salvamos esse novo usuário em uma variável user;
    const user = await User.create(data);

    await user.configuration().create({ user_id: user.id });

    //Retornamos o novo usuário como resultado da requisição, como selecionamos, no nosso caso o retorno será um JSON.
    return user;
  }

Browser other questions tagged

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