Nodejs version of orm library--sequelize
This article will take you through the nodejs database orm extension-sequelize. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
sequelize
is the nodejs version of the ORM library. Those who have usedlaravelORM
can get started quickly
[Video tutorial recommendation: node js tutorial]
Specific documentation
- Official website
- ##github
const { Sequelize, DataTypes, Model, QueryTypes, Op } = require("sequelize");
const sequelize = new Sequelize("sqlite://sql.db", { logging: false });
class User extends Model {}
class Address extends Model {}
User.init(
{
// 在这里定义模型属性
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
unique: true,
// allowNull 默认为 true
validate: {
async isUnique(name) {
const res = await User.findOne({where: {name}})
if (res) throw new Error('用户名已存在')
},
// len: [1,2]
}
},
},
{
// 这是其他模型参数
sequelize, // 我们需要传递连接实例
// modelName: "User", // 我们需要选择模型名称
tableName:'users' // 表名,默认为模型名的复数单词
}
);
Address.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
unique: true,
// allowNull 默认为 true
},
},
{
sequelize,
modelName: "Address",
}
);
// 模型关系 多对多
User.belongsToMany(Address, { through: "userAddress", as:'addres' }); // through 代表中间表的名字,as是查询别名
Address.belongsToMany(User, { through: "userAddress" });
(async () => {
try {
// await sequelize.sync({ alter: true }); // 同步模型到数据库-创建表
// const user = await User.findOne({ where: { name: {[Op.like]:'%小%'} } }); // 基本查询
const [user] = await User.findOrCreate({where:{name:'小小'},include:'addres'}); // 顺带查询到关联模型的数据
const [address] = await Address.findOrCreate({where:{name:'小小de地址'}});
await user.addAddress(address); // 关联增加
console.log(user.toJSON());
} catch (e) {
console.log(e);
}
})();
Copy after login
For more programming-related knowledge, please visit: const { Sequelize, DataTypes, Model, QueryTypes, Op } = require("sequelize"); const sequelize = new Sequelize("sqlite://sql.db", { logging: false }); class User extends Model {} class Address extends Model {} User.init( { // 在这里定义模型属性 id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, name: { type: DataTypes.STRING, unique: true, // allowNull 默认为 true validate: { async isUnique(name) { const res = await User.findOne({where: {name}}) if (res) throw new Error('用户名已存在') }, // len: [1,2] } }, }, { // 这是其他模型参数 sequelize, // 我们需要传递连接实例 // modelName: "User", // 我们需要选择模型名称 tableName:'users' // 表名,默认为模型名的复数单词 } ); Address.init( { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, name: { type: DataTypes.STRING, unique: true, // allowNull 默认为 true }, }, { sequelize, modelName: "Address", } ); // 模型关系 多对多 User.belongsToMany(Address, { through: "userAddress", as:'addres' }); // through 代表中间表的名字,as是查询别名 Address.belongsToMany(User, { through: "userAddress" }); (async () => { try { // await sequelize.sync({ alter: true }); // 同步模型到数据库-创建表 // const user = await User.findOne({ where: { name: {[Op.like]:'%小%'} } }); // 基本查询 const [user] = await User.findOrCreate({where:{name:'小小'},include:'addres'}); // 顺带查询到关联模型的数据 const [address] = await Address.findOrCreate({where:{name:'小小de地址'}}); await user.addAddress(address); // 关联增加 console.log(user.toJSON()); } catch (e) { console.log(e); } })();
Programming Teaching! !
The above is the detailed content of Nodejs version of orm library--sequelize. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Database operations in PHP are simplified using ORM, which maps objects into relational databases. EloquentORM in Laravel allows you to interact with the database using object-oriented syntax. You can use ORM by defining model classes, using Eloquent methods, or building a blog system in practice.

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Yes, Node.js can be used for front-end development, and key advantages include high performance, rich ecosystem, and cross-platform compatibility. Considerations to consider are learning curve, tool support, and small community size.
