[Fixed] How to create an object of a relationship in sequelize?

Issue

Hey I need to create a relationship in sequelize. I have the model and is well created in the database.
I’ll show you my models but it’s not very relevant.

Seller Model

const Sellers = db.define("sellers", {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  name: Sequelize.STRING,
  surname: Sequelize.STRING,
});

Sellers.hasMany(Clients);
module.exports = Sellers;

Client Model

const Client = db.define("clients", {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  name: Sequelize.STRING,
  creationDate: Sequelize.DATE,
  client_type: Sequelize.STRING,
});

module.exports = Client;

What I want to do is simply make a relation between the client and seller. In the database a SellerId is added in the client table because of sequelize hasMany() method. What I want to do is just be able to pass the id to the ORM when creating a client so it makes the relationship automatically to the seller table.

Sequelize Documentation about this

Thank you for taking your time to read this. I hope you can help me! Have a great day.

Solution

First of all I’d prefer to define a foreign key column in a model and indicate it in associations explicitly. And of course you need to add another association from clients to sellersbelongsTo and call both of associations outside models to be able to reference them to each other.

Client model file:

const Client = db.define("clients", {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  name: Sequelize.STRING,
  creationDate: Sequelize.DATE,
  client_type: Sequelize.STRING,
  sellerId: {
    type: Sequelize.INTEGER,
    allowNull: false // or true if this association is optional
  },
});

some database.js file where you should register all associations:

....
Sellers.hasMany(Clients, { foreignKey: 'sellerId' });
Clients.belongsTo(Sellers, { foreignKey: 'sellerId' });

And then you can create a client indicating a seller’s id:

const seller = await Seller.findOne({
  where: {
    name: 'Peter'
  }
})
const newClient = await Client.create({
   name: 'John',
   sellerId: seller.id,
   // other fields here
})

Leave a Reply

(*) Required, Your email will not be published