sequelize多对多研究_02

995 阅读2分钟

const moment = require('moment');
const Sequelize = require('sequelize');

//方法1:单独传递参数
const sequelize = new Sequelize('many_to_many_finally', 'root', 'root', {
    host: 'localhost',
    dialect: 'mysql',
    define: {
        timestamps: false,
        underscored: true // 配置表中字段遇到大写改_小写 下划线
    },
    timezone: '+08:00', //  解决时差 - 默认存储时间存在8小时误差
    pool: {
        max: 10, //  最大连接数量
        min: 0, //  最小连接数量
        idle: 10000 //  连接空置时间(毫秒),超时后将释放连接
    },
});
sequelize
    .authenticate()
    .then(() => {
        console.log('数据库连接成功.');
    })
    .catch(err => {
        console.error('数据库连接失败:', err);
    });
const TagModel = sequelize.define('tag', {
    tagId: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    tagName: {
        type: Sequelize.STRING(20),
        allowNull: false
    }
}, {
    freezeTableName: true
});
const PostModel = sequelize.define('post', {
    postId: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    postName: {
        type: Sequelize.STRING(20),
        allowNull: false
    }
}, {
    freezeTableName: true
});
const PostTagModel = sequelize.define('post_tag', {
    PostTagId: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    /*postIds: {
        type: Sequelize.INTEGER,
        allowNull: false,
        unique: 'post_tag'
    },
    tagIds: {
        type: Sequelize.INTEGER,
        allowNull: false,
        unique: 'post_tag',
        references: null
    }*/

}, {
    freezeTableName: true
});
sequelize.sync({
    force: false
});

// 一个post可以对应几个tag
// 一个tag也可以对应几个post
// 所以需要一个中间表记录它们之间的关系
// 表名字不能用table结尾,吃了这个亏研究了好久
PostModel.belongsToMany(TagModel, {
    through: {
        model: PostTagModel
    },
    // 基本使用一个foreignKey就好了 , foreignKey在中间表PostTagModel中当做外键(实际数据来源于PostModel),默认关联主表的主键
    foreignKey: 'postId',
    // otherKey: 'postTableIdxxxxxxx'
});

TagModel.belongsToMany(PostModel, {
    through: {
        model: PostTagModel
    },
    // 基本使用一个foreignKey就好了 , foreignKey在中间表PostTagModel中当做外键(实际数据来源于TagModel),默认关联主表的主键
    foreignKey: 'tagId',
    // otherKey: 'tagTableIdxxxxxxxxxxxx'
});
// console.log(PostModel.prototype);
// console.log(TagModel.prototype);
/*PostModel.bulkCreate([
    {
        postName: 'post_name_01'
    },
    {
        postName: 'post_name_02'
    },
    {
        postName: 'post_name_03'
    },
    {
        postName: 'post_name_04'
    }
]);
TagModel.bulkCreate([
    {
        tagName: 'tag_name_01'
    },
    {
        tagName: 'tag_name_02'
    },
    {
        tagName: 'tag_name_03'
    },
    {
        tagName: 'tag_name_04'
    }
]);*/
/*
(
    async function () {
        // const posts = await PostModel.findAll();
        let postData = await PostModel.create({
            postName: '1212121'
        });
        let tagData = await TagModel.findAll(
            {
                where: {
                    tagId: [1, 2, 3]
                }
            }
        );
        // console.log(JSON.stringify(tagData), '**************************');
        // const posts = await PostModel.findAll({
        //     where: {
        //         postId: [1, 2, 3]
        //     }
        // });
        // console.log(JSON.stringify(posts), '1111111111');
        // console.log(JSON.stringify(tags), '1111111111');
        // console.log(posts.setTags(tags), '1111111111');
        await postData.setTags(tagData);
    }
)();
*/

/*PostModel.findAll({
    where: {},
    include: [
        {
            model: TagModel
        }
    ]
}).then(result => {
    console.log(JSON.stringify(result));
});*/
/*
TagModel.findAll({
    where: {},
    include: [
        {
            model: PostModel,
            through: {
                attributes: ['postId'],
                where: {
                    postId: 5
                }
            }
        }
    ]
}).then(result => {
// 观察数据结构    console.log(JSON.stringify(result));
});
*/