javascript 如果我在表中有三个外键,我如何在User.findAll()中包含?

u3r8eeie  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(92)

我有一个有三个外键的用户。使用sequelize我如何在使用findAll时获得引用的详细信息

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define(
    'user',
    {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
      },
      name: {
        type: DataTypes.STRING,
      },
      bank: {
        type: DataTypes.STRING,
        references: {
          model: 'summary',
          key: 'id'
        }
      }
    },
    {
    
      freezeTableName: true,
      tableName: 'user'
    }
  );

  return User;
};

贷款模式

module.exports = (sequelize, DataTypes) => {
  const Loan = sequelize.define(
    'loan',
    {
      loan_id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
      },
      amoount: {
        type: DataTypes.FLOAT,
        references: {
          model: 'provider',
          key: 'id'
        }
      },
   user_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'user',
          key: 'id'
        }
      },
      guarantor_one_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'user',
          key: 'id'
        }
      },
      guarantor_two_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'user',
          key: 'id'
        }
      }
    },
    {
      freezeTableName: true,
      tableName: 'loan'
    }
  );
  Loan.associate = models => {
    Loan.belongsTo(models.User, { foreignKey: 'user_id' });
    Loan.belongsTo(models.User, { foreignKey: 'guarantor_one_id' });
    Loan.belongsTo(models.User, { foreignKey: 'guarantor_two_id' });
  };
  return Loan;
};

使用Loan.findAll检索user_id、guarantee_one_id和guarantee_two_id的所有数据的最佳方法是什么?
谢谢大家。

const loan = Loan.findAll({where : {user_id: user_id}, include: [ model: User]});

它只显示贷款中的一个用户详细信息,我希望它返回用户表上的user_id、guarantee_one_id和guarantee_two_id引用及其属性。

x0fgdtte

x0fgdtte1#

我只需要为关联使用别名,以便将它们彼此区分开来,然后在include选项中显式地指示一个别名(aliases),以帮助Sequelize理解要使用的外键/关联:

与别名的关联

Loan.associate = models => {
    Loan.belongsTo(models.User, { foreignKey: 'user_id', as: 'user' });
    Loan.belongsTo(models.User, { foreignKey: 'guarantor_one_id', as: 'guarantorOne' });
    Loan.belongsTo(models.User, { foreignKey: 'guarantor_two_id', as: 'guarantorTwo' });
  };

用法:

const loan = Loan.findAll({
  where: {
    user_id: user_id},
    include: [{
      model: User,
      as: 'user'
    },{
      model: User,
      as: 'guarantorOne'
    },{
      model: User,
      as: 'guarantorTwo'
    }
    ]
  }
);

相关问题