官網:sequelize.org/v5/manual/g…html
安裝sequelize
及數據庫鏈接驅動mysql
npm install --save sequelize
$ npm install --save mysql2
複製代碼
建立鏈接:sql
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'
});
複製代碼
建立Model表:數據庫
const Model = Sequelize.Model;
class User extends Model {}
User.init({
// attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING
// allowNull defaults to true
}
}, {
sequelize,
modelName: 'user'
// options
});
複製代碼
生產數據:npm
// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() => {
// Now the `users` table in the database corresponds to the model definition
return User.create({
firstName: 'John',
lastName: 'Hancock'
});
});
複製代碼
// Create a new user
User.create({ firstName: "Jane", lastName: "Doe" }).then(jane => {
console.log("Jane's auto-generated ID:", jane.id);
});
複製代碼
// Delete everyone named "Jane"
User.destroy({
where: {
firstName: "Jane"
}
}).then(() => {
console.log("Done");
});
複製代碼
// Change everyone without a last name to "Doe"
User.update({ lastName: "Doe" }, {
where: {
lastName: null
}
}).then(() => {
console.log("Done");
});
複製代碼
// Find all users
User.findAll().then(users => {
console.log("All users:", JSON.stringify(users, null, 4));
});
複製代碼
sequelize.org/v5/manual/d…segmentfault
對於數據遷移這塊,筆者目前實際使用仍是不熟練,好比 model
添加了新的字段如何處理、開發環境和生產環境新添加字段或者刪除字段怎麼處理 ,但願有熟悉的朋友可以指導一二,不勝感激。spa
諮詢請加微信:輕撩便可。