首页 > 解决方案 > 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'});

标签: sequelize.js

解决方案


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 道具的用户对象。


推荐阅读