sequelize.js - Sequelize中定义belongsTo关系时as和foreignKey的区别
问题描述
考虑Sequelize 文档中的以下片段
class User extends Model {}
User.init({/* attributes */}, { sequelize, modelName: 'user' })
class UserRole extends Model {}
UserRole.init({/* attributes */}, { sequelize, modelName: 'userRole' });
和有什么区别
User.belongsTo(UserRole, {as: 'role'}); // Adds roleId to user rather than userRoleId to User
和
User.belongsTo(UserRole, {foreignKey: 'roleId'}); // Adds roleId to user rather than userRoleId to User
以及为什么有人会写
User.belongsTo(UserRole, {foreignKey: 'roleId', as: 'fk_user_role'});
解决方案
User.belongsTo(UserRole, {foreignKey: 'roleId', as: 'fk_user_role'});
as:“fk_user_role”用作别名,以区分某个模型与另一个模型的关联,该模型不止一次。例如:
User.belongsTo(Organization, {foreignKey: 'organizationId', as: 'Organization'});
User.belongsTo(Organization, {foreignKey: 'headOrganizationId', as: 'HeadOrganization'});
...
User.findOne({
where: {
id: userId
},
include: [{
model: Organization,
as: 'Organization'
}, {
model: Organization,
as: 'HeadOrganization'
}]
})
你会得到一个带有 Organization 和 HeadOrganization 道具的用户对象。
推荐阅读
- node.js - 你如何制作一个可以保存和加载消息的命令
- python - 将两个数据框与分层列合并
- spring - 如何访问全局spring ObjectMapper?
- amazon-web-services - AWS 警报正在触发第二次扩展(在新任务出现之前)
- java - java:使用 Optional 优化 Java 中的 if 语句
- python - 如何将整数列表转换并保存为位图图像?
- angularjs - Yarn + Lerna + Angular Libs = 出版失败?
- c++ - 递归函数的 Matlab 代码生成
- javascript - Javascript 只能访问 Ajax 之后的一些新 DOM 有什么原因吗?
- asp.net-core - 在 ASP.NET Core Startup.cs 中访问当前用户