【问题标题】:How do you exclude and include fields in Sequelize by scope?如何按范围排除和包含 Sequelize 中的字段?
【发布时间】:2022-01-06 02:47:12
【问题描述】:
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”,并且在测试范围内我不包括“email”。我已经尝试了从exclude include 直接在findOne 调用中设置attributes 的所有内容。没有任何效果。

排除“公共”返回的某些字段并包含某种“管理范围”的所有字段的正确方法是什么?

【问题讨论】:

  • 你的 Sequelize 是什么版本?
  • @UmerAbbas 是 6.12.0

标签: node.js postgresql scope sequelize.js


【解决方案1】:

如果你有这样的defaultScope

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

当您找到查询时,它默认排除“电子邮件”并使用unscoped 禁用defaultScope

// This should not return email
UserModel.findOne()

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

或者,如果您想更加明确,可以将范围命名为“admin”。

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

这样,当你找到查询时,它默认不包括“电子邮件”。那么,如果你使用“admin”范围,它不会排除任何东西。

// This should not return email
UserModel.findOne()

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

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

【讨论】:

  • 谢谢你,admin: {} 部分解释了我做错了什么。不存在的排除会覆盖默认值。我确实在文档中发现 Scopes 适用于 .find、.findAll、.count、.update、.increment 和 .destroy,而不是 .findOne,所以这可能就是我执行 .findOne() 时没有任何效果的原因。
  • 它也应该适用于findOne。我对findOne 进行了测试并且工作正常。
  • 嗯,好的,让我重做 findOne 的功能之一并重新测试。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-30
  • 1970-01-01
相关资源
最近更新 更多