【问题标题】:How to build model with sequelize for belong to many association如何使用 sequelize 建立模型属于多关联
【发布时间】:2019-07-08 07:22:02
【问题描述】:

这是我在 Country.js 中写的(与 User.js 完全一样,除了数据类型):

module.exports = function(sequelize, DataTypes) {
    const Country = sequelize.define('country', 
    {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        code: {
            type: DataTypes.INTEGER        
        },
        alpha2: {
            type: DataTypes.STRING
        },
        alpha3: {
            type: DataTypes.STRING
        },
        name_en: {
            type: DataTypes.STRING
        },
        name_fr: {
            type: DataTypes.STRING
        }
    },
    {
        freezeTableName: true,
        timestamps: false
    });

    Country.associate = ( models ) => {
      models.Country.belongsToMany(models.User, {
        through: 'country_user',
        as: 'user',
        foreignKey: 'id_country'
      });
    };

    return Country;
}

这是我的查询:

router.get('/thisuserCountries', function(req, res, next){
    User(db, Sequelize.DataTypes).findOne({
        include: [{
            model: Country(db, Sequelize.DataTypes),
            as: 'countries',
            required: false,
            attributes: ['id'],
        }],
        where: {
            email: 'jerome.charlat@gmail.com'
        }       
    })
      .then(user => {
          if(user) {
              res.json(user)
          }
          else {
              res.send('User does not exist')
          }
      })
      .catch(err => {
          res.send('error: ' + err)
      })
})

这是我的 db.js:

const Sequelize = require('sequelize')
const db = new Sequelize('travel_memories', 'root', '', {
    host: 'localhost',
    dialect: 'mysql',
    port: 3306
})

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

const models = {
  Country: db.import('../models/Country'),
  User: db.import('../models/User'),
  CountryUserJoin: db.import('../models/Country_user')
};

Object.keys(models).forEach((modelName) => {
  if('associate' in models[modelName]){
    models[modelName].associate(models);
  }
});

module.exports = db

邮递员说:错误 SequelizeEagerLoadingError: country is not associated to user!

但是,当我在每个模型中关联表时,我认为我应该在模型 User_country 中写入 through 参数。所以我试着写一些类似的东西:

Country.associate = ( models ) => {
      models.Country.belongsToMany(models.User, {
        through: models.Country_user,
        as: 'user',
        foreignKey: 'id_country'
      });
    };

控制台说,当我启动服务器时,在查询任何内容之前:

SequelizeAssociationError: country.belongsToMany(user) 需要通过选项,传递字符串或模型。

所以我被屏蔽了。我使用文档中的示例来编写与 models.foo 的关联。但实际上模型无处可寻..

再次感谢您的帮助!

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    关于此的文档并不多,但here 它说您应该在查询或选择多属性属性时使用through 选项,就像这样:

    ...
    User(db, Sequelize.DataTypes).findOne({
      include: [{
        model: Country(db, Sequelize.DataTypes),
        as: 'countries',
        required: false,
        through: {
          attributes: ['id']
        }
      }],
      where: {
        email: 'jerome.charlat@gmail.com'
      }       
    })
    ...
    

    【讨论】:

    • 问题是我在使用这条路线之前就遇到了错误。当我启动服务器节点时。根据控制台中的错误,问题与模型相关联。这里其实是:User.associate = ({ models }) => { User.belongsToMany(Country, { through: models.Country_user ...]});
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 2019-12-12
    • 2017-03-30
    • 2020-08-12
    相关资源
    最近更新 更多