gpt4 book ai didi

sequelize.js - Sequelize中定义belongsTo关系时as和foreignKey的区别

转载 作者:行者123 更新时间:2023-12-03 22:35:49 25 4
gpt4 key购买 nike

考虑以下来自 Sequelize documentation 的片段

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

关于sequelize.js - Sequelize中定义belongsTo关系时as和foreignKey的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60852838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com