示例:
const Sequelize = require('sequelize');
// 建立连接
const sequelize = new Sequelize('test', 'root', '19931119', {
host: 'localhost',
dialect: 'mysql',//mysql 等
operatorsAiases: false
})
// 1.定义模型Model-fruits (表名,字段名,其它配置)
const Fruit = sequelize.define('fruits', {
name: Sequelize.STRING(20),
price: { type: Sequelize.FLOAT, allowNull: false },
stock: { type: Sequelize.INTEGER, defaultValve: 0 }
}, {
timestamps: false,
getterMethods: {
amount() {
return this.getDataValue('stock') + 'kg'
}
},
setterMethods: {
amount(val) {
const idx = val.indexOf('kg');
const v = val.slice(0, idx);
this.setDataValue('stock', v);
}
}
})
//同步 {force:true},强制同步
Fruit.sync({ force: true })
.then(async () => {
//插入数据
await Fruit.create({ name: '香蕉', price: 3.5 })
fruits = await Fruit.findAll()
//更新实例1 修改amount,触发setterMethods
fruits[0].amount = '16kg';
fruits[0].save();
//更新实例2
await Fruit.update({ price: 3.5 }, { where: { name: '香蕉' } })
//删除
await Fruit.destroy({ where: { name: '香蕉' } })
})
1对多查询
const Sequelize = require('sequelize');
// 建立连接
const sequelize = new Sequelize('test', 'root', '19931119', {
host: 'localhost',
dialect: 'mysql',//mysql 等
operatorsAiases: false
}) // 1:N 示例
const Player = sequelize.define('players', {
name: Sequelize.STRING(20)
})
const Team = sequelize.define('teams', {
name: Sequelize.STRING(20)
})
Player.belongsTo(Team);//放在前面 1端建立关系 查球员属于哪个球队
Team.hasMany(Player);//N端建立关系 球队有几个球员
//这里不是具体某个模型,而是sequelize实例
sequelize.sync({ force: true })
.then(async () => {
//插入数据
await Team.create({ name: '火箭' })
// await Player.create({ name: '哈登', teamId: 1 })
// await Player.create({ name: '保罗', teamId: 1 })
await Player.bulkCreate([{ name: '哈登', teamId: 1 }, { name: '保罗', teamId: 1 }]);
// 关联查询
const players = await Player.findAll({ include: [Team] })
console.log(JSON.stringify(players, null, 2));
})
多对多示例:
const Sequelize = require('sequelize');
// 建立连接
const sequelize = new Sequelize('test', 'root', '19931119', {
host: 'localhost',
dialect: 'mysql',//mysql 等
operatorsAiases: false
}) // N:N 示例
const Fruit = sequelize.define("fruits q", { name: Sequelize.STRING });
const Category = sequelize.define("categories", { name: Sequelize.STRING });
FruitCategory = Fruit.belongsToMany(Category, {
through: "FruitCategory"
});
sequelize.sync({ force: true })
.then(async () => {
// 插入测试数据
await Fruit.create(
{
name: "香蕉",
categories: [{ id: 1, name: "热带" }, { id: 2, name: "温带" }]
}, {
include: [FruitCategory]
}
);
// 多对多联合查询
const fruits = await Fruit.findOne({
where: { name: "香蕉" }, // 通过through指定条件、字段等
include: [{ model: Category, attributes: ['id', 'name'] }]
});
console.log(JSON.stringify(fruits, null, 2));
})