【问题标题】:Trying to join parent / primary table to child / foreign table in sequelize试图在续集中将父/主表连接到子/外部表
【发布时间】:2021-10-12 16:30:59
【问题描述】:

我正在尝试从文章表中获取我的所有文章数据,但也从我制作的用户表中获取用户数据。我使用 sequelize 将数据库构建到 MySQL 数据库并作为 ORM,这是 sn-p 代码

用户表

    const User = sequelize.define('users', ({
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false,
  },
  nama: {
    type: DataTypes.STRING(50),
    allowNull: false,
  },
  email: {
    type: DataTypes.STRING(50),
    allowNull: false,  
  },
  password: {
    type: DataTypes.STRING(50),
    allowNull: false,
  }
}))

文章代码

    const Articles = sequelize.define('articles', ({
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false,
  },
  title: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: false
  },
  gambar: {
    type: DataTypes.STRING,
    allowNull: false
  },
  userId: {
    type: DataTypes.BIGINT,
    allowNull: false,
  }
}))

关系

    User.hasMany(Articles, {
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE',
})
Articles.belongsTo(User, {
  foreignKey: 'userId'
})

我尝试过的 ORM

Articles.findAll({
    include: [User]
  })

总是返回 users 表没有关联到文章

【问题讨论】:

    标签: mysql express sequelize.js


    【解决方案1】:

    创建关系时必须使用关键字。

    Articles.belongsTo(User, {
     as: 'user',
     foreignKey: 'userId'
    })
    

    然后更新表单

    Articles.findAll({include: [{
     model: model.User,
     as: 'user'
    }]})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多