如何解决包含的 Sequelize 属性覆盖 defaultScope
我有这个模型吧,像这样定义
const Bar = sequelize.define(
'Bar',{
id: DataTypes.STRING,name: DataTypes.STRING,},{
defaultScope: {
attributes: ['id']
},scopes: {
withName: {
attributes: {
include: ['name']
}
}
}
}
);
当我将它包含在查找中时,它会被添加,只显示 id
Foo.findAll({
include: [{
model: Bar,// defaultScope does its work
}],})
/*
{
...
Bar:[
{
id: qux
}
]
}
*/
到目前为止,一切都很好 但是当我还想包括 Bar 的 name 字段时,id 不会被返回。
Foo.findAll({
include: [{
model: Bar,attributes: { include: ['name'] } // defaultScope get ignored
}],})
/*
{
...
Bar:[
{
name: quux
}
]
}
*/
然而,我可以创建第二个范围并与默认范围一起请求它,但是每次创建单独的范围会变得很麻烦
Foo.findAll({
include: [{
model: Bar.scope(['defaultScope','withName']) // extra scope 'withName' means extra upkeep/maintenance on the model every time you want extra fields
}],})
/*
{
...
Bar:[
{
id: qux,name: quux
}
]
}
*/
有没有一种方法可以将字段添加到 findAll(或 findOne 或 findByPk)上的包含项中,而不必每次都定义单独的范围?
我知道我可以在属性中添加我想要的 defaultScope 的字段,但这会破坏 defaultScope 的全部目的
Foo.findAll({
include: [{
model: Bar,attributes: { include: ['id','name'] } // defeats the purpose of defaultScope
}],name: quux
}
]
}
*/
编辑:或者覆盖行为是续集中的错误吗? (我在 5.21.4 上运行这个,我还没有测试过 6+)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com(将#修改为@)