创建模型(表)
1 let User = sequelize.define('user', {
2 id: {
3 type: Sequelize.INTEGER,
4 primaryKey: true,
5 autoIncrement: true
6 },
7 name: {
8 type: Sequelize.STRING,
9 allowNull: false,
10 unique: true,
11 },
12 age: {
13 type: Sequelize.TINYINT,
14 defaultValue: 66,
15 },
16 gender: {
17 type: Sequelize.ENUM(['男', '女']),
18 defaultValue: '男',
19 }
20 });
1 let Book = sequelize.define('book', {
2 id: {
3 type: Sequelize.INTEGER,
4 primaryKey: true,
5 autoIncrement: true
6 },
7 name: {
8 type: Sequelize.STRING,
9 allowNull: false,
10 unique: true
11 },
12 price: {
13 type: Sequelize.DOUBLE,
14 defaultValue: 66,
15 },
16 userId: { // 外键
17 type: Sequelize.INTEGER,
18 allowNull: false
19 }
20 });
建立一对多的关系
1 // 一个用户拥有多本书
2 User.hasMany(Book, { // 谁拥有多个谁
3 foreignKey: 'userId', // 外键
4 sourceKey: 'id', // 外键引用字段
5 });
6 // 一本书属于一个用户
7 Book.belongsTo(User, { // 谁属于谁
8 foreignKey: 'userId', // 外键
9 sourceKey: 'id', // 外键引用的字段
10 });
创建表并插入数据
1 ;(async () => {
2 // 根据模型创建表
3 await sequelize.sync({force: true});
4 // 插入数据
5 await User.create({
6 id: 1,
7 name: 'zs',
8 age: 33,
9 gender: '男'
10 });
11 await Book.create({
12 id: 1,
13 name: 'javascript',
14 price: 99.99,
15 userId: 1
16 });
17 await Book.create({
18 id: 2,
19 name: 'sequelize',
20 price: 66.66,
21 userId: 1
22 });
23 })();
关联查询
1 // 在上述22行后新增
2 const u = await User.findOne({
3 where: {
4 id: 1
5 },
6 // 关联查询 在查询用户的时候可以将对应的书查询出来
7 include: {
8 model: Book
9 }
10 });
11 console.log(u.dataValues.books);
1 // 同上
2 const b = await Book.findOne({
3 where: {
4 id: 1,
5 },
6 // 关联查询 在查询书的时候将对应的用户查询出来
7 include: {
8 model: User
9 }
10 });
11 console.log(b.dataValues.user.dataValues);
- 只有建立了表与表的关系 才能通过 include 关联查询出来
- 没有建立表与表的关系 不能通过 include 查询出来