本文主要介绍的内容为一对多的关系如何进行绑定与查询,首先添加一对多的数据,添加 book 表即可:

Sequelize-关联查询中

INSERT INTO `demo`.`book` (`id`, `name`, `price`, `uId`) VALUES (4, '玩转.net', 66, 1);
INSERT INTO `demo`.`book` (`id`, `name`, `price`, `uId`) VALUES (5, '玩转Less', 66, 4);
INSERT INTO `demo`.`book` (`id`, `name`, `price`, `uId`) VALUES (6, '玩转Sass', 66, 5);

官方文档:https://sequelize.org/v5/class/lib/associations/has-one.js~HasOne.html

Sequelize-关联查询中

// 4.建立查询关系
// 一个人拥有多本书
User.hasMany(Book, {
    foreignKey: 'uId',
    sourceKey: 'id'
});

// 一本书属于一个人
Book.belongsTo(User, {
    foreignKey: 'uId',
    sourceKey: 'id'
});
let user = await User.findOne({
    where: {
        id: 1
    },
    include: {
        model: Book
    }
});

console.log(user.dataValues.books.map(b => b.dataValues));

Sequelize-关联查询中

let book = await Book.findOne({
    where: {
        id: 1
    },
    include: {
        model: User
    }
});

console.log(book.dataValues.user.dataValues);

Sequelize-关联查询中

相关文章:

  • 2021-11-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-24
  • 2021-06-15
猜你喜欢
  • 2021-12-31
  • 2021-11-30
  • 2022-02-21
  • 2022-12-23
  • 2021-05-26
  • 2022-12-23
  • 2021-11-30
相关资源
相似解决方案