隔离两个表之间的关联 [英] Sequelize associations between two tables

查看:51
本文介绍了隔离两个表之间的关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此非常陌生(使用sequelize),一切对我来说都是新的.事实是,我可以通过"users.model.js"创建并吸引用户,但现在我想创建一个名为"data.model.js"的模型,以将某些数据与特定用户相关联.

I am fairly new to this (using sequelize) and everything is new to me. The thing is that I can create and get users through my "users.model.js" but now I want to create a model called "data.model.js" to associate some data to a certain user.

因此,根据后续文档,我的关联应为:

So according to the sequelize docs, my associations should be the following:

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

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

But when sequelize creates my tables, I don't have my foreign key in my data table.

我将与您分享我的代码

配置文件(config.js):

config file (config.js):

const Sequelize = require('sequelize');

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

module.exports = connection;

data.model.js:

data.model.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:

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;

我相信,当我尝试关联表时,我做错了,因为我觉得自己做错了方法.

I believe that when I am trying to associate my tables I am doing something wrong, because I feel that I am doing it the wrong way.

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

I don't know but everything works besides this.

但这就像我刚说的一样,我是xD续集的新手

But it's like what I said in the beginning, I am new to sequelize xD

推荐答案

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

I think the reason is circular reference. user.model.js requires data.model.js, and data.model.js requires user.model.js.

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

You need to create an index.js file. Require and make the associations for all models here, then re-export them. E.g.

./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.js controller.js :

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

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

Remove below codes in your model file:

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

这篇关于隔离两个表之间的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆