如何在 sequelize 中获取数据的深度嵌套?

How do I get deep nesting of data in sequelize?

我试图在单个查询中获取嵌套数据结构,但是在使用一对一时,数据丢失了。

数据模型:

const User = sequelize.define('user', { name: DataTypes.STRING });
const Organization = sequelize.define('organization', { name: DataTypes.STRING });
const Bank = sequelize.define('bank', { name: DataTypes.STRING });
const Tax = sequelize.define('tax', { name: DataTypes.STRING });
const BankDescription = sequelize.define('bankDescription', { description: DataTypes.STRING });
 
User.belongsTo(Organization);
Organization.hasMany(User);
Organization.hasOne(Bank);
Bank.belongsTo(Organization);
Bank.belongsTo(Tax);
Bank.hasOne(BankDescription);
BankDescription.belongsTo(Bank);

构建包含关联的查询:

const user = await User.findByPk(id, {
      include: [
        {
          association: Organization,
          include: [
            {
              association: Bank,
              include: [
                { association: Tax },
                { association: BankDescription},
              ],
            },
          ],
        },
      ],
})

输出:

{
    name: 'Don',
    organization: {
    name: 'MZZ',
    bank: {},
  },
}

但是await user.organization.bank.getBankDescription()await user.organization.bank.getTax()return数据。

如果查询将是:

const user = await User.findByPk(id, {
      include: [
        {
          association: Organization,
          include: [
            {
              association: Bank,
              include: [
                { association: Tax },
              ],
            },
          ],
        },
      ],
})

输出将是:

{
    name: 'Don',
    organization: {
    name: 'MZZ',
    bank: {
      tax: {
        name: 'fix'
     }
   },
  },
}

为什么会这样? 哪里出错了?

您的查询没有使用正确的语法。 include 属性 应该是一个对象或一个对象数组。对于每个包含的模型,您应该使用 model 属性,如果您需要指定特定关系,则应使用 as 属性。如果你想为关系使用 LEFT JOIN(这样他们就不需要 return 结果 User 那么你还应该指定 required: false.

const user = await User.findByPk(id, {
  // this include could be an object instead of an array
  include: {
    // use `model` to specify the model
    model: Organization,
    include: {
      model: Bank,
      // if you wanted to specify a particular association use the same `as` property
      /* as: 'bank', */
      include: [
        // make Tax optional with a LEFT JOIN via required: false
        { model: Tax, required: false },
        // without required this is a JOIN, so BankDescription is required
        { model: BankDescription },
      ],
    },
  },
});