Simple-SQL-Model 是一个基于 Node.js 的简单 ORM 工具。它提供了针对 SQL 数据库的 Model 操作,而不需要编写 SQL 语句。
安装
通过 npm
安装:
npm install simple-sql-model
使用
配置
在使用 Simple-SQL-Model 之前需要配置数据库连接,支持 MySQL 数据库和 PostgreSQL 数据库。
-- -------------------- ---- ------- ----- - ----- - - ---------------------------- -------------- -------- -------- -- ----------- - -------- --------- ---------------- -- ----- --------- ----------- -- ------ --------- ----------- -- -- ----- ------------ -- ----- ----- ------ -- --- ---展开代码
定义 Model
使用 Simple-SQL-Model,需要定义数据表对应的 Model。
-- -------------------- ---- ------- ----- - ----- - - ---------------------------- ----- ---- ------- ----- - -- ------------------- ------ --- ------ - ------ -------- - -- ------------ --- ---------- ------ --- ------------ - ------ - --- - ----- ---------- ----------- ----- -------------- ---- -- ----- --------- ------ - ----- --------- ------- ---- - -- - -展开代码
基本操作
定义好 Model 之后,即可进行数据库的基本操作,包括创建、查询、更新和删除。
创建
使用 create
方法创建一条数据。
-- -------------------- ---- ------- ----- -------- ------------ - ----- ---- - --- ------ ----- ----- ------ ---------------------- --- ----- ------ - ----- -------------- -------------------- -- - --- -- ----- ----- ------ ---------------------- - -展开代码
查询
使用 find
方法查询数据。
async function fetchUser() { const user = await User.find(1); console.log(user); // { id: 1, name: '张三', email: 'zhangsan@example.com' } }
使用 findAll
方法查询所有数据。
async function fetchAllUsers() { const users = await User.findAll({ where: { name: '张三' } }); console.log(users); // [ { id: 1, name: '张三', email: 'zhangsan@example.com' } ] }
使用 findOne
方法查询符合条件的第一条数据。
async function fetchOneUser() { const user = await User.findOne({ where: { name: '张三' } }); console.log(user); // { id: 1, name: '张三', email: 'zhangsan@example.com' } }
更新
使用 update
方法更新数据。
async function updateUser() { const user = await User.find(1); user.email = 'zhangsan-new@example.com'; const result = await user.update(); console.log(result); // { id: 1, name: '张三', email: 'zhangsan-new@example.com' } }
删除
使用 destroy
方法删除数据。
async function deleteUser() { const user = await User.find(1); const result = await user.destroy(); console.log(result); // true }
总结
Simple-SQL-Model 是一个简单易用的 ORM 工具,包含基本的操作支持。学习和使用它不仅能简化代码工作量,还能提升开发效率。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/6005596781e8991b448d6e92