4

I use sequelize-cli to auto generate code for model Student:

module.exports = (sequelize, DataTypes) => {
  var _stu = sequelize.define('stu', {
    name: DataTypes.STRING,
    password: DataTypes.STRING,
    gender: DataTypes.INTEGER,
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
      }
    }
  });
  return _stu
};

My question are

  1. How to get model named stu? As the sequelize is defined in function signature.

When sequelize model:generate,sequelize read config in config.json,where dbname,passowrd are specified.

  1. How the sequelize in the function signature knows database connection config,say,name,password,etc as I don't specify in this js file.
吴环宇
  • 337
  • 1
  • 6
  • 13

3 Answers3

2

Answer for question 1: "sequelize.import" will do this job.

Try this code:

const Sequelize = require('sequelize')
const sequelize = new Sequelize(...)

const stu = sequelize.import('./models/stu')

stu.findAll.then(...)
tgarm
  • 473
  • 3
  • 8
1

When you generate models via the CLI, it creates a handy models/index.js file that handles passing in a Sequelize instance for you. You can simply require cherry picked, existing models via ES6 destructuring like this:

var { stu } = require("./models");

stu.findAll().then(...);

Alternatively, you could require them all at once, and then access specific models as needed:

var models = require("./models");

models.stu.findAll().then(...);
Joost Schuur
  • 4,417
  • 2
  • 24
  • 39
0

The way i make it works was importing model with the require() function and then call it with required parameters.

Explanation

By require function you will get another function that returns your model.

module.exports = (sequelize, DataTypes) => {
  const stu = sequelize.define('stu', {
    // ...database fields
  }, {});
  stu.associate = function(models) {
    // associations can be defined here
  };
  return sty;
} // note that module.exports is a function

Now, this function requires the initialized sequelize object and a DataTypes object, so you just have to pass the instance of sequelize and Sequelize.DataTypes and then it will return your model, example:

const Sequelize = require('sequelize');
const sequelize = new Sequelize(...);

const Stu = require('./models/stu')(sequelize, Sequelize.DataTypes);

Finally you can get your database rows with Stu.findAll().

Hope this can help you.

Community
  • 1
  • 1
lerichard_v
  • 401
  • 3
  • 8