如何按范围排除和包括Sequelize中的字段


const getMe = await UserModel.scope("test").findOne({
where: {
uid: uid,
},
include: [
{
model: GroupModel,
as: "groups",
include: ["product"],
},
],
});

我正在尝试管理基于范围的排除字段和允许字段。

defaultScope: {
attributes: {
exclude: ["id"],
},
},
scopes: {
test: {
atrributes: {
exclude: ["email"],
},
},
},

协会

UserModel.hasMany(GroupModel, { as: "groups" });
Groupmodel.belongsTo(UserModel, {
foreignKey: "userId",
as: "user",
});
GroupModel.belongsTo(ProductModel, {
foreignKey: "productId",
as: "product",
});

作为测试,我默认排除";id";,并且在我所排除的测试范围中;电子邮件";。我已经尝试了从excludeinclude直接在findOne调用中设置attributes的所有操作。什么都不管用。

排除某些字段的正确方法是什么;公开的";返回,并包括"0"的所有字段;管理范围";是什么?

如果您有这样的defaultScope

defaultScope: {
attributes: {
exclude: ['email']
}
}

当您确实找到查询时,它会排除";电子邮件";默认情况下使用CCD_ 6禁用CCD_。

// This should not return email
UserModel.findOne()
// Admin case: unscoped to disable defaultScope. This should return email.
UserModel.unscoped().findOne()

或者,如果您希望更明确,您可以将作用域命名为";管理员";。

{
defaultScope: {
attributes: {
exclude: ['email']
}
},
scopes: {
admin: {}  // No special options for admin scope. No exclusion. 
}
}

这样,当您确实找到查询时,它将排除";电子邮件";默认情况下。然后,如果使用";管理员";范围,它不会排除任何东西。

// This should not return email
UserModel.findOne()
// Admin case: This should overwrite the defaultScope.
UserModel.scope('admin').findOne()

.scope(str)函数覆盖defaultScope,因此使用.scope(str)时会忽略defaultScope中的任何选项。

最新更新