无法使用sequelize将id插入到属于外键引用表的表中

uajslkp6  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(397)

我正在使用node js构建无服务器应用程序,并使用claudiaapi builder作为框架在aws中启动api。
在app.js文件中,我将所需的api调用为

const ApiBuilder = require('claudia-api-builder');
const api = new ApiBuilder();
module.exports = api;

api.post('/api/auth/validatephonenumber', async function (request) 
{
    return new Promise((resolve, reject) => {
        index.loadDatabase().then((db) => {
            resolve(loginController.validatePhonenumber(db, request));
        });
    });
});

下面是我的代码:

async function validatePhonenumber(db, request) {
return new Promise(
    async (resolve, reject) => {
        let emailid;            
        await db.EmailRegistration.sync().then(function () {
             emailid = db.EmailRegistration.findOne({
                where: { email: { [Op.eq]: mailid } },
                attributes: ['id'],
            });
        });
        if (emailid != null) {
            console.log(`email id: ${emailid.id}`);
            await db.ContactDetails.sync().then(function () {
                db.ContactDetails.findOrCreate({
                    where: { contactnumber: phnum },
                    defaults: { EmailRegistrationId: emailid.id },
                }).spread((contactdetails, created) => {
                    console.log(`contactdetails: ${contactdetails}`);
                    if (contactdetails !== null) {
                        resolve({ statuscode: indexController.statusCode.statusOK, contactdetails: contactdetails })
                    } else {
                        reject({ statuscode: indexController.statusCode.InternalServerError, message: 'phone number not created' });
                    }
                });
            });
        };
    });
}

我正在尝试将emailregistration表的emailregistrationid作为外键引用添加到contactdetails表中。我正在使用sequelize和mysql,nodejs来达到预期的效果。但是,我得到以下错误:
未处理的拒绝sequelizeforeignkeyconstrainterror:无法添加或更新子行:外键约束失败( inmeeydb . ContactDetails ,约束 ContactDetails_ibfk_1 外键( EmailRegistrationId )参考文献 EmailRegistration ( id )删除级联更新级联)
下面是我的电子邮件注册模型文件:

const moment = require('moment');

module.exports = (sequelize, DataTypes) => {
const EmailRegistration = sequelize.define(
'EmailRegistration',
{
  id: {
    type: DataTypes.UUID,
    primaryKey: true,
    allowNull: false,
    defaultValue: DataTypes.UUIDV4,
  },
  email: {
    type: DataTypes.STRING(50),
    allowNull: false,
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: { min: 6 },
  },
  createdAt: {
    type: DataTypes.DATE,
    get() {
      return moment.utc(new Date(), 'DD/MM/YYYY h:mm a').format('DD/MM/YYYY h:mm a');
    },
  },
  updatedAt: {
    type: DataTypes.DATE,
    defaultValue: null,       
  },
},
{
  freezeTableName: true,
}
);

EmailRegistration.associate = function (models) {
    EmailRegistration.hasOne(models.ContactDetails,
        { foreignKey: 'EmailRegistrationId' }
    );
};

return EmailRegistration;
};

下面是我的contactdetails模型文件:

const moment = require('moment');

module.exports = (sequelize, DataTypes) => {
const ContactDetails = sequelize.define(
'ContactDetails',
{
  id: {
    type: DataTypes.UUID,
    primaryKey: true,
    allowNull: false,
    defaultValue: DataTypes.UUIDV4,
  },
  contactnumber: { type: DataTypes.STRING(13), allowNull: false },
  isverified: { type: DataTypes.BOOLEAN, defaultValue: false },
  createdAt: {
    type: DataTypes.DATE,
    get() {
      return moment.utc(new Date(), 'DD/MM/YYYY h:mm a').format('DD/MM/YYYY h:mm a');
    },
  },
  updatedAt: {
    type: DataTypes.DATE,
    defaultValue: null,        
  },
},
{
  indexes: [{ fields: ['contactnumber'], unique: true }],
},
{
  freezeTableName: true,
}
);

ContactDetails.associate = function(models) {
ContactDetails.belongsTo(models.EmailRegistration, {
  onDelete: 'CASCADE',
  hooks: true,
  foreignKey: { allowNull: false },
});
};   

return ContactDetails;
};

我试着用两个表中的引用修改下面的代码,但都没用。

ContactDetails.associate = function(models) {
    ContactDetails.belongsTo(models.EmailRegistration,
    { foreignKey: 'EmailRegistrationId' }
    );
};

无法分析如何克服这个问题。当我将nodejs与expressjs一起使用时,它工作得很好,没有任何问题。它无法在contactdetails表中标识emailregistrationid(查询中缺少该ID),并将输出显示为

INSERT INTO `ContactDetails` (`id`,`contactnumber`,`isverified`,`createdAt`,`updatedAt`) VALUES ('52974e07-8489-4101-ab71-6af874903290','+xxxxxxxxx',false,'2018-10-12 08:55:35','2018-10-12 08:55:35');
wlwcrazw

wlwcrazw1#

您需要更新关联的配置。这个 ContactDetails 模型现在将有一个名为 emailregistrationid ```
EmailRegistration.associate = function (models) {
EmailRegistration.hasMany(models.ContactDetails);
};

ContactDetails.associate = function(models) {
ContactDetails.belongsTo(models.EmailRegistration, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'emailregistrationid'
allowNull: false
},
});
}

ContactDetails.create({
...
emailregistrationid: <some_valid_emailregistrationid>
})

相关问题