How to Relationship in Seeds and Factories in Adonisjs

Asked

Viewed 481 times

1

I have the following question regarding Seeds and Factories.

I have the following scenario: When the user is created automatically I need to create a settings record in the Userconfig table with the user’s FK.

In the controller I create this way:

class UserController {
  async store({ request }) {
    //Buscamos os campos do corpo da nossa requisição e os armazenamos em um objeto chamado data;
    const data = request.only([
      "name",
      "last_name",
      "date_birth",
      "cpf",
      "cep",
      "address",
      "uf",
      "city",
      "cellphone",
      "phone",
      "email",
      "password"
    ]);

    //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);

    //Criando os dados de configuração do usuário
    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;
  }

In this case I do a user search for the past email, get the user, access his id and create the settings record with this user_id.

But how do I make the seeder go the same way? How I get user data after creating it through the seeder?

Actually I did something like this:

Factory.js

/** @type {import('@adonisjs/framework/src/Hash')} */
const Hash = use("Hash");

/** @type {import('@adonisjs/lucid/src/Factory')} */
const Factory = use("Factory");

Factory.blueprint("App/Models/Plan", async faker => {
  return {
    name: faker.name(),
    description: "testes",
    price: 20.99
  };
});

Factory.blueprint("App/Models/User", async faker => {
  return {
    plan_id: 1,
    name: faker.name(),
    email: faker.name() + "@gmail.com",
    password: await Hash.make(faker.password())
  };
});

Factory.blueprint("App/Models/Configuration", async faker => {
  return {
    user_id:  <-----Caso eu insira um valor fixo aqui é criado dois registros no banco um com o ID inserido e outro com ID original do usuario.
  };
});

How do I pass the created user id value?

Seeders

class ConfigurationSeeder {
  async run() {
    await Factory.model("App/Models/Configuration").create();
  }
}

----------------------------------------------------------------------

class UserSeeder {
  async run() {
    const user = await Factory.model("App/Models/User").create();
    console.log(user);
  }
}

----------------------------------------------------------------------

class PlanSeeder {
  async run() {
    await Factory.model("App/Models/Plan").create();
  }

1 answer

1

Resolved as follows:

Removed from Factory.js as Factories.Blueprint Settings, and also removed the settings and plans Seeds files.

My file Factory.js was as follows:

/** @type {import('@adonisjs/framework/src/Hash')} */
const Hash = use("Hash");

/** @type {import('@adonisjs/lucid/src/Factory')} */
const Factory = use("Factory");

Factory.blueprint("App/Models/Plan", async faker => {
  var data = new Date();
  return {
    name: faker.name(),
    description: "testes",
    price: 20.99,
    expiration_date: data.toLocaleDateString("pt-BR")
  };
});

Factory.blueprint("App/Models/User", async faker => {
  return {
    plan_id: 1,
    name: faker.name(),
    email: faker.name() + "@gmail.com",
    password: await Hash.make(faker.password())
  };
});

After that it was changed to Userseeder.js as follows:

/** @type {import('@adonisjs/lucid/src/Factory')} */
const Factory = use("Factory");

class UserSeeder {
  async run() {
    const plan = await Factory.model("App/Models/Plan").create();
    const user = await Factory.model("App/Models/User").make();
    await user.plan().associate(plan);
    await user.configuration().create({ user_id: user.id });
  }
}

module.exports = UserSeeder;

Done this, when running Adonis Seed user is created along with the records of plans and settings for each user with their particular relationships.

User will always have to be linked to a single plan, ie a plan needs to exist before creating the user; A user after being created will need to have relationship with their only personal settings record in the table of Configurations;

Browser other questions tagged

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