首页 > 解决方案 > 序列化两个表之间的关联

问题描述

我对此相当陌生(使用续集),一切对我来说都是新的。问题是我可以通过我的“users.model.js”创建和获取用户,但现在我想创建一个名为“data.model.js”的模型来将一些数据与某个用户相关联。

所以根据sequelize docs,我的关联应该如下:

Users.hasMany(Data)
Data.belongsTo(Users)

但是当 sequelize 创建我的表时,我的数据表中没有我的外键。

我将与您分享我的代码:

配置文件(config.js):

const Sequelize = require('sequelize');

const connection = new Sequelize('drglicemia', 'root', '', {
host: 'localhost',
dialect: 'mysql'
});

module.exports = connection;

数据模型.js:

const sequelize = require('sequelize');
const db = require('../config/database');
const usersTable = require('./users.model')

let Data = db.define('tabeladados', {
    dta: { type: sequelize.DATEONLY },
    hora: { type: sequelize.DATE },
    indiceglicemia: { type: sequelize.STRING },
    insulina: { type: sequelize.STRING },
    medicacao: { type: sequelize.STRING },
}, {
    timeStamps: false, tableName: 'tabeladados'
});

//associates the dataTable table with the users
Data.associate = () => {
    Data.belongsTo(usersTable)
}


module.exports = Data;

users.model.js:

const sequelize = require('sequelize');
const promise = require('bluebird')
const bcrypt = promise.promisifyAll(require('bcrypt'))
const db = require('../config/database');
const dataTable = require('./data.model')

let Users = db.define('utilizadores', {
    username: { type: sequelize.STRING },
    email: { type: sequelize.STRING },
    password: { type: sequelize.STRING },
}, {
    timeStamps: false, tableName: 'utilizadores',
});


//encrypts the password before submiting to the database
Users.beforeCreate((user, options) => {

    return bcrypt.hash(user.password, 10)
        .then(hash => {
            user.password = hash;
        })
        .catch(err => {
            throw new Error();
        });
});

//validates the password submited by the user with the one encrypted in the database
Users.prototype.validPassword = async (password) => {
    return await bcrypt.compare(password, this.password);
}

//associates the users table with the dataTable
Users.associate = () => {
    Users.hasMany(dataTable)
}

module.exports = Users;

我相信当我试图关联我的表时,我做错了,因为我觉得我做错了。

我不知道,但除此之外一切正常。

不过就像我一开始说的,我是新来续集的xD

标签: javascriptmysqlnode.jsexpresssequelize.js

解决方案


我认为原因是循环引用user.model.js需要data.model.js,并且data.model.js需要user.model.js

您需要创建一个index.js文件。要求并在此处为所有模型建立关联,然后重新导出它们。例如

./models/index.js

const User = require('./user.model.js');
const Data = require('./data.model.js');

User.hasMany(Data);
Data.belongsTo(User);

module.exports = {User, Data}

service.jscontroller.js

const models = require('./models/index.js');
// use models
await models.User.findAll();

删除模型文件中的以下代码:

// Remove from user.model.js file
Users.associate = () => {
    Users.hasMany(dataTable)
}
// Remove from data.model.js file
Data.associate = () => {
    Data.belongsTo(usersTable)
}

推荐阅读