Alex Bran
Alex Bran

Reputation: 463

node.JS / sequelize associate db tables

I am trying to associate two database tables, but I do not know exactly where to add the code in my configuration:

config.js

const Sequelize = require("sequelize");

const sequelize  = new Sequelize("training", "postgres", "test", {
    host: "localhost",
    dialect: "postgres",
    dialectOptions: {
      ssl: {
        require: true,
        rejectUnauthorized: false // <<<<<<< YOU NEED THIS
      }
    },
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000,
    },
  })

  const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;


// db.sequelize.gallery = require("../models/gallery")(DataTypes);
// db.tags = require("../models/tags.js")(sequelize, Sequelize);

// gallery.hasMany(db.tags, { as: "item" });
// db.tags.belongsTo(db.gallery, {
//   foreignKey: "item",
//   as: "item",
// });
  
module.exports = { db, JWT_SECRET: "secretString",}

If I add the commented code here I get the error that require is not a function.

This is how my models look like: gallery.js

const { db } = require("../config/configProvider")();
module.exports = function(DataTypes) {
  const Gallery = db.sequelize.define(
    "items",
    {

      // },
      date: {
        type: DataTypes.DATE(),
        // required: true,
      },
      url: {
        type: DataTypes.STRING,
        // required: true,
      },
      description: {
        type: DataTypes.STRING,
      },
      location: {
        type: DataTypes.STRING,
      },
      rating: {
        type:DataTypes.INTEGER,
      }
    },
    { timestamps: false }
  );


  return Gallery;
};

index.js

const sequelize = require("sequelize");
const DataTypes = sequelize.DataTypes;
const Types = require("./models/types")(sequelize, DataTypes);
const Tags = require("./models/tags")(sequelize, DataTypes);

config.db.sequelize
  .authenticate()
  .then(() => {
    console.log("Connection has been established successfully.");
  })
  .catch((err) => {
    console.error("Unable to connect to the database:", err);
  });

If I create index.js in models (where I could add the db associations, how would I call it in main file index.js?

Upvotes: 1

Views: 392

Answers (1)

Wang Liang
Wang Liang

Reputation: 4444

gallery.js

Gallery.associate = function(models) {
    gallery.hasMany(db.tags, { as: "item" });
};

tag.js

Tag.associate = function (models) {
    tags.belongsTo(db.gallery, {
        foreignKey: "item",
        as: "item",
    });
}

Upvotes: 2

Related Questions