1

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?

1 Answer 1

2

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",
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.