sequelize使用坑

报错:hasOne Cannot add foreign key constraint

  • 使用多表查询的时候,必须在建表后再使用
Student.sync(); // 先同步表
Student.hasMany(Info, {foreignKey: 'studentId'}); // 同步表以后就可以使用了

Student.sync({force:true}); // 先同步表
Student.hasMany(Info, {foreignKey: 'studentId'}); // 这样会报hasOne Cannot add foreign key constraint

#后期新增字段如何处理

  • test.js
const Sequelize = require('sequelize');
const { createSchema } = require('../config/db');

const TABLENAME = 'role';
const FIELDS = {
  name: {
    type: Sequelize.STRING,
  },
  nameZh: {
    type: Sequelize.STRING,
    field: 'name_zh',
  },
  test:{
    type: Sequelize.STRING
  }
};
const Role = createSchema(TABLENAME, FIELDS);
Role.sync({alter: true});  // 即可添加新的字段
module.exports = { Role };



你可能感兴趣的:(sequelize)