我想以正式方式在父模型的字段中包含模型。
const Item = sequelize.define('item',
{
type: Sequelize.STRING,
subItemId: Sequelize.INTEGER
}
);
const ItemA = sequelize.define('itema',
{
name: Sequelize.STRING
}
);
const ItemB = sequelize.define('itemb',
{
name: Sequelize.STRING
}
);
const start = async () => {
await Item.sync({ force: true });
await ItemA.sync({ force: true });
await ItemB.sync({ force: true });
Item.belongsTo(ItemA, { foreignKey: 'subItemId', constraints: false });
Item.belongsTo(ItemB, { foreignKey: 'subItemId', constraints: false });
Item.addScope('defaultScope', {
include: [
{ model: ItemA, required: false, where: ['`item`.`type`="A"'] },
{ model: ItemB, required: false, where: ['`item`.`type`="B"'] }
],
}, { override: true });
await Item.create({ type: 'A', subItemId: 1 });
await Item.create({ type: 'b', subItemId: 1 });
await ItemA.create({ id: 1, name: 'itemA' });
await ItemB.create({ id: 1, name: 'itemB' });
const itemInstance = await Item.findOne({ where: { id: 1 } });
// itemInstance.itemb === null
};
start();
我知道代码可以正常工作,但是如果有人在某个地方包含item
,就像BigBox include Box include Item
。由于item.type
是BigBox.Box.Item.type
的别名,因此将引发错误。
那么,有什么正式的方法吗?