Personal blog address: monkey code notes

1. EggJS Sequelize reference

  1. Install the Sequelize dependencies and mysql driver

    cnpm i egg-sequelize mysql2 -S
    Copy the code
  2. Enable the Sequelize plug-in

    Add it in config/plugin.js

    sequelize: {
        enable: true,
        package: 'egg-sequelize',},Copy the code
  3. Configuring the Database

    Add it in config/config.default.js

    config.sequelize = {
        dialect: 'mysql'.// Mysql is used
        host: '127.0.0.1'.// Address of the connected database host
        port: 3306.// Mysql service port
        database: 'demo'.// Database name
        username: 'root'.// Database user name
        password: 'root'.// Database password
        define: {  // Global configuration of the model
          	timestamps: true.// Add create,update,delete timestamp
          	paranoid: true.// Add soft delete
          	freezeTableName: true.// Prevent table names from changing to plural
          	underscored: false  // Prevent camelback fields from being changed to underscores by default
        },
        timezone: From the '+'.// Because of the UTC time used by orM, the east 8 region must be added here, otherwise the time difference is 8 hours
        dialectOptions: {  // Make reading data of type date return a string instead of the UTC time
            dateStrings: true,
            typeCast(field, next) {
                if (field.type === "DATETIME") {
                    return field.string();
                }
                returnnext(); }}};Copy the code

2. Define the Model

  1. The initial egg project is built using egg-init without the app/model directory. The initial project structure is as follows:

    Itzishu ├ ─ ─ the README. Md ├ ─ ─ app │ ├ ─ ─ controller │ │ └ ─ ─ home. Js │ └ ─ ─ the router. The js ├ ─ ─ appveyor. Yml ├ ─ ─ the config │ ├ ─ ─ ├─ ├─ 07.02.txt ├─ 07.02.txtCopy the code

    Create a new directory named Model under app directory, which is used to store the instance object contents of all tables defined in the database.

  2. The contents of the database table are as follows:

    /*
     Navicat Premium Data Transfer
    
     Source Server         : 系统数据库3306
     Source Server Type    : MySQL
     Source Server Version : 50725
     Source Host           : localhost:3306
     Source Schema         : demo
    
     Target Server Type    : MySQL
     Target Server Version : 50725
     File Encoding         : 65001
    
     Date: 12/05/2019 15:11:37
    */
    
    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    
    -- ----------------------------
    -- Table structure for classes
    -- ----------------------------
    DROP TABLE IF EXISTS `classes`;
    CREATE TABLE `classes` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `name` varchar(50) NOT NULL,
      `createdAt` datetime DEFAULT NULL,
      `updatedAt` datetime DEFAULT NULL,
      `deletedAt` datetime DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
    
    -- ----------------------------
    -- Records of classes
    -- ----------------------------
    BEGIN;
    INSERT INTO `classes` VALUES (1, '软件工程1601', '2019-05-12 13:11:43', '2019-05-12 13:11:47', NULL);
    INSERT INTO `classes` VALUES (2, '网络工程1601', '2019-05-12 13:12:10', '2019-05-12 13:12:13', NULL);
    COMMIT;
    
    -- ----------------------------
    -- Table structure for info
    -- ----------------------------
    DROP TABLE IF EXISTS `info`;
    CREATE TABLE `info` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `name` varchar(50) NOT NULL,
      `age` int(11) NOT NULL,
      `sex` tinyint(255) NOT NULL DEFAULT '1' COMMENT '1为男,0为女',
      `studentId` int(11) NOT NULL,
      `createdAt` datetime DEFAULT NULL,
      `updatedAt` datetime DEFAULT NULL,
      `deletedAt` datetime DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;
    
    -- ----------------------------
    -- Records of info
    -- ----------------------------
    BEGIN;
    INSERT INTO `info` VALUES (1, '许仙', 23, 1, 1, '2019-05-12 13:25:58', '2019-05-12 13:26:01', NULL);
    INSERT INTO `info` VALUES (2, '白素贞', 20, 0, 2, '2019-05-12 13:26:41', '2019-05-12 13:26:46', NULL);
    INSERT INTO `info` VALUES (3, '法海', 22, 1, 3, '2019-05-12 13:27:20', '2019-05-12 13:27:22', NULL);
    INSERT INTO `info` VALUES (4, '小青', 18, 0, 4, '2019-05-12 13:27:48', '2019-05-12 13:27:51', NULL);
    INSERT INTO `info` VALUES (5, '金如意', 20, 0, 5, '2019-05-12 13:28:34', '2019-05-12 13:28:37', NULL);
    INSERT INTO `info` VALUES (6, '景松', 23, 1, 6, '2019-05-12 13:30:07', '2019-05-12 13:30:10', NULL);
    COMMIT;
    
    -- ----------------------------
    -- Table structure for lession
    -- ----------------------------
    DROP TABLE IF EXISTS `lession`;
    CREATE TABLE `lession` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `name` varchar(50) NOT NULL,
      `createdAt` datetime DEFAULT NULL,
      `updatedAt` datetime DEFAULT NULL,
      `deletedAt` datetime DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
    
    -- ----------------------------
    -- Records of lession
    -- ----------------------------
    BEGIN;
    INSERT INTO `lession` VALUES (1, '计算机网络', '2019-05-12 13:12:32', '2019-05-12 13:12:35', NULL);
    INSERT INTO `lession` VALUES (2, 'Java程序设计', '2019-05-12 13:12:50', '2019-05-12 13:12:52', NULL);
    INSERT INTO `lession` VALUES (3, '软件项目管理', '2019-05-12 13:13:07', '2019-05-12 13:13:10', NULL);
    INSERT INTO `lession` VALUES (4, '网络安全', '2019-05-12 13:13:22', '2019-05-12 13:13:25', NULL);
    COMMIT;
    
    -- ----------------------------
    -- Table structure for lession_student
    -- ----------------------------
    DROP TABLE IF EXISTS `lession_student`;
    CREATE TABLE `lession_student` (
      `lessionId` int(11) NOT NULL,
      `studentId` int(11) NOT NULL,
      `createdAt` datetime DEFAULT NULL,
      `updatedAt` datetime DEFAULT NULL,
      `deletedAt` datetime DEFAULT NULL,
      PRIMARY KEY (`lessionId`,`studentId`) USING BTREE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    
    -- ----------------------------
    -- Records of lession_student
    -- ----------------------------
    BEGIN;
    INSERT INTO `lession_student` VALUES (1, 1, '2019-05-12 13:20:35', '2019-05-12 13:20:40', NULL);
    INSERT INTO `lession_student` VALUES (1, 2, '2019-05-12 13:20:51', '2019-05-12 13:20:53', NULL);
    INSERT INTO `lession_student` VALUES (1, 3, '2019-05-12 13:21:02', '2019-05-12 13:21:05', NULL);
    INSERT INTO `lession_student` VALUES (1, 4, '2019-05-12 13:21:15', '2019-05-12 13:21:19', NULL);
    INSERT INTO `lession_student` VALUES (1, 5, '2019-05-12 13:21:29', '2019-05-12 13:21:32', NULL);
    INSERT INTO `lession_student` VALUES (1, 6, '2019-05-12 13:21:43', '2019-05-12 13:21:45', NULL);
    INSERT INTO `lession_student` VALUES (2, 1, '2019-05-12 13:23:10', '2019-05-12 13:23:13', NULL);
    INSERT INTO `lession_student` VALUES (2, 3, '2019-05-12 13:23:28', '2019-05-12 13:23:31', NULL);
    INSERT INTO `lession_student` VALUES (2, 4, '2019-05-12 13:23:40', '2019-05-12 13:23:43', NULL);
    INSERT INTO `lession_student` VALUES (2, 5, '2019-05-12 13:23:54', '2019-05-12 13:23:57', NULL);
    INSERT INTO `lession_student` VALUES (3, 1, '2019-05-12 13:24:21', '2019-05-12 13:24:24', NULL);
    INSERT INTO `lession_student` VALUES (3, 4, '2019-05-12 13:24:39', '2019-05-12 13:24:42', NULL);
    INSERT INTO `lession_student` VALUES (4, 2, '2019-05-12 13:24:59', '2019-05-12 13:25:03', NULL);
    INSERT INTO `lession_student` VALUES (4, 6, '2019-05-12 13:25:12', '2019-05-12 13:25:15', NULL);
    COMMIT;
    
    -- ----------------------------
    -- Table structure for student
    -- ----------------------------
    DROP TABLE IF EXISTS `student`;
    CREATE TABLE `student` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `number` varchar(12) NOT NULL COMMENT '学号',
      `password` varchar(32) NOT NULL,
      `classId` int(11) NOT NULL,
      `createdAt` datetime DEFAULT NULL,
      `updatedAt` datetime DEFAULT NULL,
      `deletedAt` datetime DEFAULT NULL,
      PRIMARY KEY (`id`,`number`) USING BTREE
    ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;
    
    -- ----------------------------
    -- Records of student
    -- ----------------------------
    BEGIN;
    INSERT INTO `student` VALUES (1, '160101', '202cb962ac59075b964b07152d234b70', 1, '2019-05-12 13:16:09', '2019-05-12 13:16:12', NULL);
    INSERT INTO `student` VALUES (2, '160201', '202cb962ac59075b964b07152d234b70', 2, '2019-05-12 13:16:32', '2019-05-12 13:16:35', NULL);
    INSERT INTO `student` VALUES (3, '160102', '202cb962ac59075b964b07152d234b70', 1, '2019-05-12 13:17:17', '2019-05-12 13:17:21', NULL);
    INSERT INTO `student` VALUES (4, '160103', '202cb962ac59075b964b07152d234b70', 1, '2019-05-12 13:17:51', '2019-05-12 13:17:54', NULL);
    INSERT INTO `student` VALUES (5, '160104', '202cb962ac59075b964b07152d234b70', 1, '2019-05-12 13:18:13', '2019-05-12 13:18:16', NULL);
    INSERT INTO `student` VALUES (6, '160202', '202cb962ac59075b964b07152d234b70', 2, '2019-05-12 13:18:36', '2019-05-12 13:18:39', NULL);
    COMMIT;
    
    SET FOREIGN_KEY_CHECKS = 1;
    
    Copy the code

    Among them, the relationship between each table is as follows:

    • Student has a one-to-one relationship with info
    • Classes and student have a one-to-many relationship
    • Student and Lession have a many-to-many relationship, and the intermediate table is lession_student
  3. According to the structure of the data table, we determine the relationship and write the relevant files in the model directory

    • student.js
    module.exports = app= > {
        const { STRING, INTEGER } = app.Sequelize;
    
        const Student = app.model.define('student', {
            id: {
                type: INTEGER,
                autoIncrement: true.primaryKey: true
            },
            number: {
                type: STRING,
                allowNull: false,},password: {
                type: STRING(32),
                allowNull: false
            },
            classId: {
                type: INTEGER,
                allowNull: false}}); Student.associate =function (){
            // There is a one-to-many relationship with Info, so hasOne()
            app.model.Student.hasOne(app.model.Info, {foreignKey: 'studentId'});
            // Many-to-one relationship with Classes exists, so use belongsTo()
            app.model.Student.belongsTo(app.model.Classes, {foreignKey: 'classId'.targetKey: 'id'});
            // Have a many-to-many relationship with Lessison, use belongsToMany()
            app.model.Student.belongsToMany(app.model.Lession, {
                through: app.model.LessionStudent,
                foreignKey: 'studentId'.otherKey: 'lessionId'
            });
        }
    
        return Student;
    }
    Copy the code
    • info.js
    module.exports = app= > {
        const { STRING, INTEGER, BOOLEAN } = app.Sequelize;
    
        const Info = app.model.define('info', {
            id: {
                type: INTEGER,
                autoIncrement: true.primaryKey: true
            },
            name: {
                type: STRING(50),
                allowNull: false,},age: {
                type: INTEGER,
                allowNull: false
            },
            sex: {
                type: BOOLEAN,
                allowNull: false,
                get() {
                    if ( this.getDataValue('sex') ){
                        return 'male';
                    }else {
                        return 'woman'; }}},studentId: {
                type: INTEGER,
                allowNull: false}}); Info.associate =function (){
            app.model.Info.belongsTo(app.model.Student, {foreignKey: 'studentId'.targetKey: 'id'});
        }
    
        return Info;
    }
    Copy the code

    In the sex field, there is a get(){} method, because in the table, the sex field stores 1 or 0, 1 is male and 0 is female. In order to return male or female directly, we use the get method after finding the data

    • classes.js
    module.exports = app= > {
        const { STRING, INTEGER, BOOLEAN } = app.Sequelize;
    
        const Classes = app.model.define('classes', {
            id: {
                type: INTEGER,
                autoIncrement: true.primaryKey: true
            },
            name: {
                type: STRING(50),
                allowNull: false,},age: {
                type: INTEGER,
                allowNull: false
            },
            sex: {
                type: BOOLEAN,
                allowNull: false,
                get() {
                    if ( this.getDataValue('sex') ){
                        return 'male';
                    }else {
                        return 'woman'; }}},studentId: {
                type: INTEGER,
                allowNull: false}}); Classes.associate =function (){
            // classes and student are one-to-many, so hasMany() is used here
            app.model.Classes.hasMany(app.model.Student, {foreignKey: 'classId'.targetKey: 'id'});
        }
    
        return Classes;
    }
    Copy the code
    • lession.js
    module.exports = app= > {
        const { INTEGER, STRING } = app.Sequelize;
    
        const Lession = app.model.define('lession', {
            id: {
                type: INTEGER,
                primaryKey: true.autoIncrement: true
            },
            name: {
                type: STRING,
                allowNull: false}}); Lession.associate =function(){
            // The student table is many-to-many
            app.model.Lession.belongsToMany(app.model.Student, {
                through: app.model.LessionStudent,
                foreignKey: 'lessionId'.otherKey: 'studentId'
            });
        }
    
        return Lession;
    }
    Copy the code
    • lession-student.js
    module.exports = app= > {
        const { INTEGER } = app.Sequelize;
    
        const LessionStudent = app.model.define('lession_student', {
            lessionId: {
                type: INTEGER,
                primaryKey: true
            },
            studentId: {
                type: INTEGER,
                primaryKey: true}}); LessionStudent.associate =function(){}return LessionStudent;
    }
    Copy the code
  4. Summarize the Model definition

    • Field types used by MYSQL

    The field types are obtained from app.sequelize with the following names

    Sequelize.STRING                      // VARCHAR(255)
    Sequelize.STRING(1234)                // VARCHAR(1234)
    Sequelize.STRING.BINARY               // VARCHAR BINARY
    Sequelize.TEXT                        // TEXT
    Sequelize.TEXT('tiny')                // TINYTEXT
    
    Sequelize.INTEGER                     // INTEGER
    Sequelize.BIGINT                      // BIGINT
    Sequelize.BIGINT(11)                  // BIGINT(11)
    
    Sequelize.FLOAT                       // FLOAT
    Sequelize.FLOAT(11)                   // FLOAT(11)
    Sequelize.FLOAT(11.12)               / / FLOAT (11, 12)
    
    Sequelize.DOUBLE                      // DOUBLE
    Sequelize.DOUBLE(11)                  // DOUBLE(11)
    Sequelize.DOUBLE(11.12)              / / DOUBLE (11, 12)
    
    Sequelize.DECIMAL                     // DECIMAL
    Sequelize.DECIMAL(10.2)              / / a DECIMAL (1, 2)
    
    Sequelize.DATE                        // DATETIME against mysql/sqLite, TIMESTAMP WITH TIME ZONE against postgres
    Sequelize.DATE(6)                     // DATETIME(6) for mysql 5.6.4+. Decimal seconds support up to 6 bits of accuracy
    Sequelize.DATEONLY                    // DATE does not contain time.
    Sequelize.BOOLEAN                     // TINYINT(1)
    Copy the code

    Other types allowed by databases refer to: data types

    • Field attribute value
    The property name type The default value instructions instructions
    type Any There is no is The data type
    primaryKey Boolean false no A primary key
    autoIncrement Boolean false no Since the increase
    allowNull Boolean false no Whether to allow null
    defaultValue Any There is no no The default value
    field String The field name no Custom field name
    unique Any There is no no The constraint
    • Table to table correlation

    In Sequelize, there are three coded associations between tables: one-to-one, one-to-many, and many-to-many

    1. One to one

      In this project, there is a one-to-one relationship between the student table and the INFO table, with one specific message for each student.

      In student.js, the hasOne() method is used. The first argument is the associated model object Info, and the second argument is an object containing a property foreginKey for the studentId field in the corresponding information table

      In info.js, the belongsTo() method is used. The first parameter is the associated model object Student and the second parameter is an object with two properties. ForeginKey is the “studentId” field in the info table. The second parameter, targetKey, is the “ID” field in the student table

      Conclusion: HasOne () and belongsTo() : the first parameter is a Model instance of another table that is associated with the table. In belongsTo, the second parameter has a foreginKey attribute. In hasOne, this attribute value is the corresponding column of the other table. This attribute value is the name of the field on this table that corresponds to the peer table ID. BelongsTo has a targetKey attribute that is the corresponding primary key name of the peer table

    2. More than a pair of

      Classes and student are one-to-many. A class consists of multiple students.

      In student.js, belongsTo() was used, and in classes.js, hasMany() was used. HasMany () is similar to the belongsTo() parameter, but note that The foreginKey value in hasMany() is the classesId of the other table. Combined with the above “one-to-one” analysis, we can conclude that:

      In a method that begins with HAS, the foreginKey attribute is retrieved from the peer’s table, and if there is a targetKey, it is its own primary key.

      For a method that begins with the attribution, the foreginKey attribute value is found on its own table, and the targetKey attribute value is found on the other table

    3. Many to many

      If a student has multiple courses and a class has multiple students, we can use an intermediate table lession-student.js to make this connection.

      In student.js, we use the belongsToMany() method, and in the lession.js file, we can see that it has an through property whose value is the Model instance of the intermediate table. According to the above rule, the way to the beginning of the foreginKey find yourself, otherKey find other, so it is easy to understand.

    Summary: In an instance of Model, override the associate method of Model and put the associated relationships in it.

    One to one methods are: hasOne(Model, {foreignKey: peer,}) and belongsTo(Model,{foreignKey: oneself,targetKey: peer})

    The one-to-many methods are hasMany(Model,{foreignKey: peer,targetKey: self}) and belongsTo(Model,{foreignKey: peer,targetKey: peer})

    Many-to-many methods include: belongsToMany(Model,{through:Model, targetKey: oneself, otherKey: other})

3. Query the union table

  • One to one

    So in controller, let’s say this

    // Get student information through one-to-many connections
        async info(){
            const { ctx, app } = this;
            let result = await app.model.Student.findAll({
              include: {
                model: app.model.Info
              }
            });
            ctx.body = result;
        }
    Copy the code

    The values obtained are as follows:

    / / / the first student {" id ": 1," number ":" 160101 ", "password" : "202 cb962ac59075b964b07152d234b70", "every" : 1, "createdAt" : "The 2019-05-12 13:16:09, updatedAt" : "the 2019-05-12 13:16:12", "deletedAt:" null, "info" : {/ / league table to check the information "sex" : "male", "id" : 1, "name", "x", "age" : 23, "studentId" : 1, "createdAt" : "the 2019-05-12 13:25:58", "updatedAt" : "2019-05-12 13:26:01", "deletedAt": null}}, // second student {"id": 2, "number": "160201", "password": "202cb962ac59075b964b07152d234b70", "classId": 2, "createdAt": "2019-05-12 13:16:32", "updatedAt": "The 2019-05-12 13:16:35", "deletedAt:" null, "info" : {" sex ", "female", "id" : 2, "name" : "lady bai", "age" : 20, "studentId" : 2, "createdAt": "2019-05-12 13:26:41", "updatedAt": "2019-05-12 13:26:46", "deletedAt": null } }, { "id": 3, "number": "160102", "password": "202cb962ac59075b964b07152d234b70", "classId": 1, "createdAt": "The 2019-05-12 13:17:17, updatedAt" : "the 2019-05-12 13:17:21", "deletedAt:" null, "info" : {" sex ", "male", "id" : 3, "name" : "Method", "age" : 22, "studentId" : 3, "createdAt" : "the 2019-05-12 13:27:20", "updatedAt" : "the 2019-05-12 13:27:22", "deletedAt" : null } }, { "id": 4, "number": "160103", "password": "202cb962ac59075b964b07152d234b70", "classId": 1, "createdAt": "The 2019-05-12 13:17:51, updatedAt" : "the 2019-05-12 13:17:54", "deletedAt:" null, "info" : {" sex ", "female", "id" : 4, "name" : "Xiaoqing", "age" : 18, "studentId" : 4, "createdAt" : "the 2019-05-12 13:27:48", "updatedAt" : "the 2019-05-12 13:27:51", "deletedAt" : null } }, { "id": 5, "number": "160104", "password": "202cb962ac59075b964b07152d234b70", "classId": 1, "createdAt": "The 2019-05-12 13:18:13, updatedAt" : "the 2019-05-12 13:18:16", "deletedAt:" null, "info" : {" sex ", "female", "id" : 5, "name" : "StudentId ", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId", "studentId": null } }, { "id": 6, "number": "160202", "password": "202cb962ac59075b964b07152d234b70", "classId": 2, "createdAt": "The 2019-05-12 13:18:36, updatedAt" : "the 2019-05-12 13:18:39", "deletedAt:" null, "info" : {" sex ", "male", "id" : 6, "name" : "JingSong", "age" : 23, "studentId" : 6, "createdAt" : "the 2019-05-12 13:30:07", "updatedAt" : "the 2019-05-12 13:30:10", "deletedAt" : null } } ]Copy the code
  • More than a pair of

    // Get the students of the class named Software Engineering 1601
        async student(){
          const { ctx, app } = this;
          let result = await app.model.Classes.findAll({
            where: {
              name: 'Software Engineering 1601'
            },
            include: {
              model: app.model.Student
            }
          })
          ctx.body = result;
        }
    Copy the code

    The obtained data is as follows:

    [{"id": 1."name": "Software Engineering 1601"."createdAt": "The 2019-05-12 13:11:43"."updatedAt": "The 2019-05-12 13:11:47"."deletedAt": null."students": [{"id": 1."number": "160101"."password": "202cb962ac59075b964b07152d234b70"."classId": 1."createdAt": "The 2019-05-12 13:16:09"."updatedAt": "The 2019-05-12 13:16:12"."deletedAt": null
                },
                {
                    "id": 3."number": "160102"."password": "202cb962ac59075b964b07152d234b70"."classId": 1."createdAt": "The 2019-05-12 13:17:17"."updatedAt": "The 2019-05-12 13:17:21"."deletedAt": null
                },
                {
                    "id": 4."number": "160103"."password": "202cb962ac59075b964b07152d234b70"."classId": 1."createdAt": "The 2019-05-12 13:17:51"."updatedAt": "The 2019-05-12 13:17:54"."deletedAt": null
                },
                {
                    "id": 5."number": "160104"."password": "202cb962ac59075b964b07152d234b70"."classId": 1."createdAt": "The 2019-05-12 13:18:13"."updatedAt": "The 2019-05-12 13:18:16"."deletedAt": null}}]]Copy the code
  • Many to many

    Obtain course information from students

    // Get the student's course selection
        async lession(){
          const { ctx, app } = this;
          let result = await app.model.Student.findAll({
            where: {id: 1,},include: [{model: app.model.Info},
              {model: app.model.Lession}
            ]
          });
          ctx.body = result;
        }
    Copy the code

    In this case, note that the value of include is an array, so that multiple tables can get data

    The data are as follows:

    [{"id": 1."number": "160101"."password": "202cb962ac59075b964b07152d234b70"."classId": 1."createdAt": "The 2019-05-12 13:16:09"."updatedAt": "The 2019-05-12 13:16:12"."deletedAt": null."info": {
                "sex": "Male"."id": 1."name": "X"."age": 23."studentId": 1."createdAt": "The 2019-05-12 13:25:58"."updatedAt": "The 2019-05-12 13:26:01"."deletedAt": null
            },
            "lessions": [{"id": 1."name": "Computer Network"."createdAt": "The 2019-05-12 13:12:32"."updatedAt": "The 2019-05-12 13:12:35"."deletedAt": null."lession_student": {
                        "lessionId": 1."studentId": 1."createdAt": "The 2019-05-12 13:20:35"."updatedAt": "The 2019-05-12 13:20:40"."deletedAt": null}}, {"id": 2."name": "Java Programming"."createdAt": "The 2019-05-12 13:12:50"."updatedAt": "The 2019-05-12 13:12:52"."deletedAt": null."lession_student": {
                        "lessionId": 2."studentId": 1."createdAt": "The 2019-05-12 13:23:10"."updatedAt": "The 2019-05-12 13:23:13"."deletedAt": null}}, {"id": 3."name": "Software Project Management"."createdAt": "The 2019-05-12 13:13:07"."updatedAt": "The 2019-05-12 13:13:10"."deletedAt": null."lession_student": {
                        "lessionId": 3."studentId": 1."createdAt": "The 2019-05-12 13:24:21"."updatedAt": "The 2019-05-12 13:24:24"."deletedAt": null}}]}]Copy the code

    Access to selected courses from courses:

    // Get the students participating in a class
        async lessionStudent(){
          const { ctx, app } = this;
          let result = await app.model.Lession.findAll({
            where: {name: 'Network Security'
            },
            include: {
              model: app.model.Student,
              include: {
                model: app.model.Info
              }
            }
          });
          ctx.body = result;
        }
    Copy the code

    Note here that there is an include following the include, and the second include is relative to the Student table

    The data are as follows:

    [{"id": 4."name": "Cyber Security"."createdAt": "The 2019-05-12 13:13:22"."updatedAt": "The 2019-05-12 13:13:25"."deletedAt": null."students": [{"id": 2."number": "160201"."password": "202cb962ac59075b964b07152d234b70"."classId": 2."createdAt": "The 2019-05-12 13:16:32"."updatedAt": "The 2019-05-12 13:16:35"."deletedAt": null."lession_student": {
                        "lessionId": 4."studentId": 2."createdAt": "The 2019-05-12 13:24:59"."updatedAt": "The 2019-05-12 13:25:03"."deletedAt": null
                    },
                    "info": {
                        "sex": "Female"."id": 2."name": "Bai Suzhen"."age": 20."studentId": 2."createdAt": "The 2019-05-12 13:26:41"."updatedAt": "The 2019-05-12 13:26:46"."deletedAt": null}}, {"id": 6."number": "160202"."password": "202cb962ac59075b964b07152d234b70"."classId": 2."createdAt": "The 2019-05-12 13:18:36"."updatedAt": "The 2019-05-12 13:18:39"."deletedAt": null."lession_student": {
                        "lessionId": 4."studentId": 6."createdAt": "The 2019-05-12 13:25:12"."updatedAt": "The 2019-05-12 13:25:15"."deletedAt": null
                    },
                    "info": {
                        "sex": "Male"."id": 6."name": "JingSong"."age": 23."studentId": 6."createdAt": "The 2019-05-12 13:30:07"."updatedAt": "The 2019-05-12 13:30:10"."deletedAt": null}}]}]Copy the code

4. To summarize

Four hours of debugging, database setup, coding, documentation. If I’m lazy and don’t want to summarize, I can read through the content and basically understand the basic use of Sequelize for syntable queries