zzpda 2023-05-07 23:25 采纳率: 66.7%
浏览 32
已结题

关于#node#的问题,如何解决?

node.js sequelize 多表查询
三个模型:
1.学生模型,包含 id,name
2.分数模型,包含id,studentId,分数
3.爱好模型,包含id,studentId,爱好
请问在sequelize中如何查询出学生的姓名,分数及爱好?官网介绍的都是二个表的关联查询,三个或更多的就没有说了!

  • 写回答

2条回答 默认 最新

  • 菜喵007 2023-05-08 09:09
    关注
    
    const Student = sequelize.define('student', {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false
      }
    });
    
    const Score = sequelize.define('score', {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      score: {
        type: DataTypes.INTEGER,
        allowNull: false
      }
    });
    
    const Hobby = sequelize.define('hobby', {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      hobby: {
        type: DataTypes.STRING,
        allowNull: false
      }
    });
    
    // 关系配置
    Student.hasMany(Score);
    Score.belongsTo(Student);
    
    Student.hasMany(Hobby);
    Hobby.belongsTo(Student);
    
    // 查询学生、分数和爱好
    Student.findAll({
      attributes: ['name'],
      include: [{
        model: Score,
        attributes: ['score']
      }, {
        model: Hobby,
        attributes: ['hobby']
      }]
    })
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 9月20日
  • 已采纳回答 9月12日
  • 创建了问题 5月7日