我在我的 Node js 应用程序中使用sequelize。所有模型都在名为
user.js
、message.js
等的单独文件中定义。我还有自动生成的 index.js
文件,这是其中的一个片段,您可能会认出它:
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
所以我正在看sequelize的关联手册这里。 我不知道在我的情况下这会去哪里,因为我使用的是自动生成的
index.js
文件,它收集了所有 models
。在他们的示例中,正如您在链接上看到的,他们有类似的内容:
const A = sequelize.define('A', /* ... */);
const B = sequelize.define('B', /* ... */);
A.hasOne(B); // A HasOne B
A.belongsTo(B); // A BelongsTo B
A.hasMany(B); // A HasMany B
A.belongsToMany(B, { through: 'C' });
当我的模型分布在多个文件中时,我该如何做同样的事情?我尝试过这样的事情(例如,在消息模型中):
return sequelize.define('message', {
message_id: {
type: DataTypes.BIGINT,
allowNull: false,
autoIncrement:true,
primaryKey: true
},
user_id: {
type: DataTypes.BIGINT,
allowNull: true
}
// and other stuff..
}, {
tableName: 'message'
}).hasOne(require('./user'));
};
这给出了一个错误: message.hasOne 调用的东西不是 Sequelize.Model
的子类有什么想法吗?
谢谢。
我是这样做的:
module.exports = (sequelize, DataTypes) => {
const MyEntity = sequelize.define(
'MyEntity',
{
name: DataTypes.STRING
},
{}
);
MyEntity.associate = function(models) {
// associations can be defined here
MyEntity.hasMany(models.OtherEntity, {
foreignKey: 'myEntityId',
as: 'myEntities'
});
};
return MyEntity;
};
这是另一种选择。经过多次尝试和失败
希望能帮助别人
// there must be the default express generated models/index.js
// user.js
const { Model } = require('sequelize')
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {
User.hasMany(models.Restaurant, {
as: 'restaurants',
foreignKey: { name: 'user_id', type: DataTypes.UUID },
})
}
}
User.init({
id: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
},
// ...
}, {
sequelize,
modelName: 'User',
tableName: 'users',
paranoid: true,
})
return User
}
restaurant.js
const {
Model,
} = require('sequelize')
module.exports = (sequelize, DataTypes) => {
class Restaurant extends Model {
static associate(models) {
Restaurant.belongsTo(models.User, {
foreignKey: { name: 'user_id', type: DataTypes.UUID },
as: 'user',
})
}
}
Restaurant.init({
id: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
},
user_id: {
type: DataTypes.INTEGER,
allowNull: false,
field: 'user_id',
},
// ...
}, {
sequelize,
modelName: 'Restaurant',
tableName: 'restaurants',
paranoid: true,
})
return Restaurant
}
// in the consumer app.js
const { User, Restaurant } = require('../../models/index')
//...
const user = await User.findOne({ where: { id }, include: { model: Restaurant, as: 'restaurants' } })
const response = {
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
restaurants: user.restaurants,
}
return response