我试图通过一个已经在mySql中创建的新表来关联2个表。然后,我可以从API获取所需的数据。与新表链接的2个表是用户和国家。用户可以访问许多国家。一个国家可以被许多用户访问。
这是我的模型User.js:
const Sequelize = require('sequelize')
const db = require('../database/db.js')
const Country = require('./Country')
const User = db.sequelize.define('user',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING
},
firstName: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
admin: {
type: Sequelize.TINYINT
}
},
{
freezeTableName: true,
timestamps: false,
});
User.associate = () => {
User.belongsToMany(Country, {
through: 'Country_user',
as: 'country',
foreignKey: 'id_user'
});
};
module.exports = User
这是我的模型Country.js:
const Sequelize = require('sequelize')
const db = require('../database/db.js')
const User = require('./User')
const Country = db.sequelize.define('country',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
code: {
type: Sequelize.INTEGER
},
alpha2: {
type: Sequelize.STRING
},
alpha3: {
type: Sequelize.STRING
},
name_en: {
type: Sequelize.STRING
},
name_fr: {
type: Sequelize.STRING
}
},
{
freezeTableName: true,
timestamps: false
});
Country.associate = () => {
Country.belongsToMany(User, {
through: 'Country_user',
as: 'user',
foreignKey: 'id_country'
});
};
module.exports = Country;
这是我的模型Country_user.js:
const Sequelize = require('sequelize')
const db = require('../database/db.js')
const Country_user = db.sequelize.define('country_user', {
id_user: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'User',
key: 'id'
}
},
id_country: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'Country',
key: 'id'
}
}
});
module.exports = Country_user
最后,这是我的查询,以获取我需要的数据:
var express = require('express')
var router = express.Router()
const User = require('../../models/User')
const Country = require('../../models/Country')
router.get('/user', function(req, res, next){
User.findAll({
include: [{
model: Country,
as: 'country',
attributes: ['id', 'name_fr'],
through: { attributes: [] }
}]
})
.then(user => {
res.json(user)
})
.catch(err => {
res.send('error: ' + err)
})
})
module.exports = router
我希望ORM不会在数据库中创建新字段。我已经创建了它们。我只想将这些外键链接到ORM中的右表,以便可以轻松获取数据。
当我尝试使用路由/ user时,我是从POSTMAN那里获得的:
错误:SequelizeEagerLoadingError:国家与用户未关联!
编辑:db.js文件的构建方式如下:
const Sequelize = require('sequelize')
const db = {}
const sequelize = new Sequelize('travel_memories', 'root', '', {
host: 'localhost',
dialect: 'mysql',
port: 3306
})
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
答案 0 :(得分:0)
您是否通过这样的方式运行模型?
Object.keys(models).forEach((modelName) => {
if ('associate' in models[modelName]) {
// console.log(models[modelName]);
models[modelName].associate(models);
}
});
要真正建立关联??仅在“国家和用户”中添加belongsToMany关联逻辑是不够的
我的models目录中有一个索引文件,它会执行类似的操作,我将为您进行一些修改,您需要将“ path_to”语句替换为您的正确路径。...< / p>
import { Sequelize } from 'sequelize';
import sequelize from '../../helpers/db';
const models = {
Country: sequelize.import('./path_to_country'),
User: sequelize.import('./path_to_user'),
CountryUserJoin: sequelize.import('./path_to_join')
};
Object.keys(models).forEach((modelName) => {
if ('associate' in models[modelName]) {
// console.log(models[modelName]);
models[modelName].associate(models);
}
});
models.sequelize = sequelize;
models.Sequelize = Sequelize;
export default models;
答案 1 :(得分:0)
const Sequelize = require('sequelize')
const db = {}
const sequelize = new Sequelize('travel_memories', 'root', '', {
host: 'localhost',
dialect: 'mysql',
port: 3306
})
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
const models = {
Country: sequelize.import('../../models/Country'),
User: sequelize.import('../../models/User'),
CountryUserJoin: sequelize.import('../../models/Country_user')
};
Object.keys(models).forEach((modelName) => {
if ('associate' in models[modelName]) {
// console.log(models[modelName]);
models[modelName].associate(models);
}
});
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
答案 2 :(得分:0)
这是我在自己的js文件中编写我的方式的方法:
module.exports = function (sequelize, DataTypes) {
const Country = sequelize.define('loc_countries', {
id: {
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
allowNull: true,
},
abbr2: {
type: DataTypes.STRING,
allowNull: true,
},
abbr3: {
type: DataTypes.STRING,
allowNull: true,
},
}, {
freezeTableName: true,
timestamps: false,
tableName: 'loc_countries',
});
Country.associate = function (models) {
models.Country.hasMany(models.ProvinceState, { as: 'ProvStates', foreignKey: 'loc_countries_id' });
};
return Country;
};