Sắp xếp lại MySQL

ORM (Object-Relational Mapping) là một kỹ thuật cho phép truy vấn và thao tác dữ liệu bằng cách sử dụng một đối tượng tới lớp ánh xạ quan hệ. Ngày nay, có rất nhiều thư viện ORM có sẵn và hầu hết các nhà phát triển thích sử dụng chúng hơn các truy vấn SQL thô

ORM giúp các nhà phát triển viết các truy vấn phức tạp một cách nhanh chóng và giúp cập nhật và sử dụng lại mã dễ dàng hơn

Tuy nhiên, việc bắt đầu với ORM có thể khó khăn do đường cong học tập. Vì vậy, đây là hướng dẫn nhanh về cách thiết lập Sequelize ORM với Node. js và MySQL

Phần tiếp theo là gì

Sắp xếp lại MySQL

Sequelize là một thư viện ORM dựa trên lời hứa dành riêng cho Node. js. Nó được giới thiệu lần đầu tiên vào năm 2011 và hiện tại, nó đã có hơn 1. 1 triệu lượt tải xuống NPM hàng tuần và hơn 25 nghìn sao GitHub

So với các thư viện ORM khác, Sequelize ổn định hơn và có nhiều tính năng khác nhau như truy vấn, quan hệ, giao dịch, hook, phạm vi, di chuyển, v.v. Ngoài ra, nó hỗ trợ nhiều cơ sở dữ liệu như MySQL, MariaDB, SQLite, Microsoft SQL Server và Postgres

Đối với hướng dẫn này, chúng tôi sẽ tập trung vào việc sử dụng Sequelize với Node. js và MySQL

Sử dụng Sequelize với một nút. js và MySQL

Trong hướng dẫn này, chúng tôi sẽ thực hiện như sau

  • Khởi tạo một nút. dự án js với Express. js, Phần tiếp theo và MySQL
  • Tạo các mô hình Sequelize
  • Viết truy vấn với Sequelize

Bạn sẽ cần có hiểu biết cơ bản về Node. js và MySQL trước khi bạn bắt đầu

Bước 1. Tạo một nút mới. dự án js

Đầu tiên, bạn cần khởi tạo một Node mới. ứng dụng js. Bạn có thể sử dụng lệnh

package name: (nodejs-sequelize-example)
version: (1.0.0)
description: example-project
entry point: (index.js)
test command:
git repository:
keywords: node.js, orm, sequelize, mysql
author: Layercode
license: (ISC){
   “name”: “nodejs-sequelize-example”,
   “version”: “1.0.0”,
   “description”: “example-project”,
   “main”: “index.js”,
   “scripts”: {
     “test”: “echo \”Error: no test specified\” && exit 1"
   },
   “keywords”: [
     “node.js”, “orm”,“sequelize”, “mysql”
   ],
   “author”: “chameera”,
   “license”: “ISC”
}Is this OK? (yes)
1 để khởi tạo ứng dụng mới

npm init

Nó sẽ nhắc một chế độ xem như bên dưới nơi bạn cần nhập một số chi tiết như tên, phiên bản, mô tả và tác giả

package name: (nodejs-sequelize-example)
version: (1.0.0)
description: example-project
entry point: (index.js)
test command:
git repository:
keywords: node.js, orm, sequelize, mysql
author: Layercode
license: (ISC){
   “name”: “nodejs-sequelize-example”,
   “version”: “1.0.0”,
   “description”: “example-project”,
   “main”: “index.js”,
   “scripts”: {
     “test”: “echo \”Error: no test specified\” && exit 1"
   },
   “keywords”: [
     “node.js”, “orm”,“sequelize”, “mysql”
   ],
   “author”: “chameera”,
   “license”: “ISC”
}Is this OK? (yes)

Bước 2. Cài đặt Sequalize và các thư viện khác

Bạn cần cài đặt Sequalize và các thư viện bên thứ ba khác cho dự án. Trong hướng dẫn này, chúng tôi sẽ sử dụng các thư viện serialize , express, cors và mysql2. (Bạn cũng có thể sử dụng thư viện mysql thay vì mysql2)

// Express npm install express --save// Sequalize npm install sequelize --save// MySQL npm install mysql2 --save// CORS npm install cors --save

Dưới đây là một bản tóm tắt nhanh về những gì các thư viện trên làm

Bước 3. Thiết lập máy chủ Express

Thể hiện. js là một khung ứng dụng web nguồn mở cho Node. js. Nó cung cấp các tính năng sẵn có khác nhau để giúp các nhà phát triển triển khai các ứng dụng web một cách hiệu quả. Vì vậy, chúng tôi cũng sẽ sử dụng Express. js trong ví dụ này

Bước đầu tiên để thiết lập máy chủ Express, bạn cần tạo một tệp mới có tên máy chủ. js. Sau đó, bạn có thể thực hiện tất cả các cấu hình cần thiết như bật Chia sẻ tài nguyên nguồn gốc chéo (CORS), phân tích cú pháp hoặc xác định các cổng trong tệp này bằng Express

const express = require(“express”); const cors = require(“cors”);const app = express();var corsOptions = { origin: “http://localhost:4200" // URL of the frontend };app.use(cors(corsOptions)); app.use(express.json()); // parsing application/json app.use(express.urlencoded({ extended: true })); // parsing application/x-www-form-urlencodedconst PORT = process.env.PORT || 8080; // Portapp.listen(PORT, () => { console.log(`Server is running on port ${PORT}.`); });

Khi tất cả các cấu hình đã sẵn sàng, bạn có thể mở một thiết bị đầu cuối và kiểm tra ứng dụng bằng lệnh

package name: (nodejs-sequelize-example)
version: (1.0.0)
description: example-project
entry point: (index.js)
test command:
git repository:
keywords: node.js, orm, sequelize, mysql
author: Layercode
license: (ISC){
   “name”: “nodejs-sequelize-example”,
   “version”: “1.0.0”,
   “description”: “example-project”,
   “main”: “index.js”,
   “scripts”: {
     “test”: “echo \”Error: no test specified\” && exit 1"
   },
   “keywords”: [
     “node.js”, “orm”,“sequelize”, “mysql”
   ],
   “author”: “chameera”,
   “license”: “ISC”
}Is this OK? (yes)
2. Nếu không có lỗi, bạn sẽ thấy thông báo;

Bước 4. Khởi tạo Sequelize và kết nối cơ sở dữ liệu

Bây giờ, bạn cần cấu hình kết nối cơ sở dữ liệu MySQL và khởi tạo Sequelize

Ở đây, chúng tôi đã tạo một tệp mới có tên

package name: (nodejs-sequelize-example)
version: (1.0.0)
description: example-project
entry point: (index.js)
test command:
git repository:
keywords: node.js, orm, sequelize, mysql
author: Layercode
license: (ISC){
   “name”: “nodejs-sequelize-example”,
   “version”: “1.0.0”,
   “description”: “example-project”,
   “main”: “index.js”,
   “scripts”: {
     “test”: “echo \”Error: no test specified\” && exit 1"
   },
   “keywords”: [
     “node.js”, “orm”,“sequelize”, “mysql”
   ],
   “author”: “chameera”,
   “license”: “ISC”
}Is this OK? (yes)
4 trong thư mục
package name: (nodejs-sequelize-example)
version: (1.0.0)
description: example-project
entry point: (index.js)
test command:
git repository:
keywords: node.js, orm, sequelize, mysql
author: Layercode
license: (ISC){
   “name”: “nodejs-sequelize-example”,
   “version”: “1.0.0”,
   “description”: “example-project”,
   “main”: “index.js”,
   “scripts”: {
     “test”: “echo \”Error: no test specified\” && exit 1"
   },
   “keywords”: [
     “node.js”, “orm”,“sequelize”, “mysql”
   ],
   “author”: “chameera”,
   “license”: “ISC”
}Is this OK? (yes)
5. Thư mục này sẽ chứa tất cả các model mà chúng ta tạo ở bước tiếp theo, và file
package name: (nodejs-sequelize-example)
version: (1.0.0)
description: example-project
entry point: (index.js)
test command:
git repository:
keywords: node.js, orm, sequelize, mysql
author: Layercode
license: (ISC){
   “name”: “nodejs-sequelize-example”,
   “version”: “1.0.0”,
   “description”: “example-project”,
   “main”: “index.js”,
   “scripts”: {
     “test”: “echo \”Error: no test specified\” && exit 1"
   },
   “keywords”: [
     “node.js”, “orm”,“sequelize”, “mysql”
   ],
   “author”: “chameera”,
   “license”: “ISC”
}Is this OK? (yes)
4 dùng để khởi tạo Sequelize

Trước tiên, bạn cần nhập Sequalize và tạo một phiên bản mới bằng cách cung cấp tên cơ sở dữ liệu, tên người dùng, máy chủ lưu trữ mật khẩu và cấu hình nhóm

const Sequelize = require("sequelize");const sequelize = new Sequelize(DATABASE, USER, PASSWORD, { host: HOST, dialect: mysql, operatorsAliases: false, pool: { max: 5, min: 0, idle: 10000 } });const db = {}; db.Sequelize = Sequelize; db.sequelize = sequelize; module.exports = db;

Sau đó, bạn có thể tạo các mô hình Sequelize và nhập chúng vào tệp này

Bước 5. Tạo các mô hình Sequelize

Bạn có thể tạo các mô hình Sequelize trong thư mục

package name: (nodejs-sequelize-example)
version: (1.0.0)
description: example-project
entry point: (index.js)
test command:
git repository:
keywords: node.js, orm, sequelize, mysql
author: Layercode
license: (ISC){
   “name”: “nodejs-sequelize-example”,
   “version”: “1.0.0”,
   “description”: “example-project”,
   “main”: “index.js”,
   “scripts”: {
     “test”: “echo \”Error: no test specified\” && exit 1"
   },
   “keywords”: [
     “node.js”, “orm”,“sequelize”, “mysql”
   ],
   “author”: “chameera”,
   “license”: “ISC”
}Is this OK? (yes)
5. Ở đây, chúng tôi đã tạo một mô hình có tên
package name: (nodejs-sequelize-example)
version: (1.0.0)
description: example-project
entry point: (index.js)
test command:
git repository:
keywords: node.js, orm, sequelize, mysql
author: Layercode
license: (ISC){
   “name”: “nodejs-sequelize-example”,
   “version”: “1.0.0”,
   “description”: “example-project”,
   “main”: “index.js”,
   “scripts”: {
     “test”: “echo \”Error: no test specified\” && exit 1"
   },
   “keywords”: [
     “node.js”, “orm”,“sequelize”, “mysql”
   ],
   “author”: “chameera”,
   “license”: “ISC”
}Is this OK? (yes)
8 với 4 trường. Các trường này đại diện cho các cột trong cơ sở dữ liệu MySQL và bảng sẽ được tạo tự động bằng khóa chính

module.exports = (sequelize, Sequelize) => { const Article = sequelize.define(“article”, { title: { type: Sequelize.STRING }, subtitle: { type: Sequelize.STRING }, author: { type: Sequelize.STRING }, published: { type: Sequelize.BOOLEAN } }); return Article; };

Sau đó, bạn cần nhập mô hình này vào tệp

package name: (nodejs-sequelize-example)
version: (1.0.0)
description: example-project
entry point: (index.js)
test command:
git repository:
keywords: node.js, orm, sequelize, mysql
author: Layercode
license: (ISC){
   “name”: “nodejs-sequelize-example”,
   “version”: “1.0.0”,
   “description”: “example-project”,
   “main”: “index.js”,
   “scripts”: {
     “test”: “echo \”Error: no test specified\” && exit 1"
   },
   “keywords”: [
     “node.js”, “orm”,“sequelize”, “mysql”
   ],
   “author”: “chameera”,
   “license”: “ISC”
}Is this OK? (yes)
4

...const db = {}; db.Sequelize = Sequelize; db.sequelize = sequelize;db.articles = require(“./article.model”)(sequelize, Sequelize); module.exports = db;

Cuối cùng, nhập chỉ mục. js lên máy chủ. js và đồng bộ hóa chúng với cơ sở dữ liệu bằng Sequelize. Máy chủ được cập nhật. js sẽ tương tự như bên dưới

const express = require(“express”); const cors = require(“cors”); const app = express(); var corsOptions = { origin: “http://localhost:4200" }; app.use(cors(corsOptions)); app.use(express.json()); app.use(express.urlencoded({ extended: true })); const db = require("./app/models/index.js"); db.sequelize.sync(); const PORT = process.env.PORT || 8080; // Port app.listen(PORT, () => { console.log(`Server is running on port ${PORT}.`); });

Bước 6. Viết truy vấn với Sequelize

Bạn có thể bắt đầu viết truy vấn với Sequelize. Ở đây, chúng tôi đã tạo một bộ điều khiển có tên

// Express npm install express --save// Sequalize npm install sequelize --save// MySQL npm install mysql2 --save// CORS npm install cors --save

0 trong thư mục

// Express npm install express --save// Sequalize npm install sequelize --save// MySQL npm install mysql2 --save// CORS npm install cors --save

1 và chúng tôi sẽ hướng dẫn bạn cách viết các thao tác CRUD cơ bản

Sequelize cung cấp một tập hợp các chức năng được xác định để xử lý các hoạt động CRUD

  • (đối tượng) — Tạo bản ghi mới
  • (id) — Tìm một bản ghi theo khóa chính
  • () — Tìm tất cả bản ghi
  • (dữ liệu, ở đâu. { Tôi. id }) — Cập nhật bản ghi theo id
  • (ở đâu. { Tôi. id }) — Xóa bản ghi theo id
  • (ở đâu. {}) — Xóa tất cả bản ghi

Trước tiên, bạn cần nhập các mô hình có liên quan vào bộ điều khiển. Sau đó, bạn có thể sử dụng các mô hình có chức năng Sequelize để viết các truy vấn như bên dưới

const db = require(“../models”); const Article = db.articles; const Op = db.Sequelize.Op;// Create Articleexports.create = (req, res) => { const article = { title: req.body.title, subtitle: req.body.subtitle, author: req.body.author, published: req.body.published ? req.body.published : false }; Article.create(article) .then(data => { res.send(data); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while creating the Tutorial." }); }); }; // Find Single Articleexports.findOne = (req, res) => { const id = req.params.id; Article.findByPk(id) .then(data => { if (data) { res.send(data); } else { res.status(404).send({ message: `Cannot find Article with id=${id}.` }); } }) .catch(err => { res.status(500).send({ message: "Error retrieving Article with id=" + id }); }); }; // Update Articleexports.update = (req, res) => { const id = req.params.id; Article.update(req.body, { where: { id: id } }) .then(num => { if (num == 1) { res.send({ message: "Article was updated successfully." }); } else { res.send({ message: `Cannot update Article with id=${id}.` }); } }) .catch(err => { res.status(500).send({ message: "Error updating Article with id=" + id }); }); }; // Delete Articleexports.delete = (req, res) => { const id = req.params.id; Article.destroy({ where: { id: id } }) .then(num => { if (num == 1) { res.send({ message: "Article was deleted successfully!" }); } else { res.send({ message: `Cannot delete Article with id=${id}.` }); } }) .catch(err => { res.status(500).send({ message: "Could not delete Article with id=" + id }); }); };

Bước 7. Xác định tuyến đường

Bước cuối cùng, bạn cần tạo route cho các thao tác CRUD ở trên. Ở đây, chúng tôi đã tạo một tệp tuyến đường có tên là bài viết. tuyến đường. js trong thư mục ứng dụng/tuyến đường

module.exports = app => { const articles = require(“../controllers/article.controller.js”); var router = require(“express”).Router(); // Create a new Article router.post(“/”, articles.create); // Retrieve a single Article with id router.get(“/:id”, articles.findOne); // Update a Article with id router.put(“/:id”, articles.update); // Delete a Article with id router.delete(“/:id”, articles.delete); app.use(‘/api/articles’, router);};

Bộ định tuyến Express được sử dụng để xử lý định tuyến và tất cả các điểm cuối liên quan đến bài viết đều có tiền tố là api/articles. Sau đó, bạn cần nhập các tuyến này vào máy chủ. js ngay trước định nghĩa cổng. Máy chủ được cập nhật. js sẽ trông giống như bên dưới

package name: (nodejs-sequelize-example)
version: (1.0.0)
description: example-project
entry point: (index.js)
test command:
git repository:
keywords: node.js, orm, sequelize, mysql
author: Layercode
license: (ISC){
   “name”: “nodejs-sequelize-example”,
   “version”: “1.0.0”,
   “description”: “example-project”,
   “main”: “index.js”,
   “scripts”: {
     “test”: “echo \”Error: no test specified\” && exit 1"
   },
   “keywords”: [
     “node.js”, “orm”,“sequelize”, “mysql”
   ],
   “author”: “chameera”,
   “license”: “ISC”
}Is this OK? (yes)
0

Về cơ bản là vậy. Bạn đã tạo thành công một Nút. js với Sequelize và MySQL. Bạn có thể khởi động lại ứng dụng và kiểm tra các điểm cuối với Postman

MySQL có hỗ trợ Sequelize không?

Sequelize chỉ hỗ trợ cơ sở dữ liệu quan hệ. Các cơ sở dữ liệu như Mongo DB hoặc các cơ sở dữ liệu NoSQL khác không được hỗ trợ . Sequelize hỗ trợ giao dịch chắc chắn, tải háo hức và lười biếng, quan hệ, sao chép đọc và các tính năng thú vị khác.

Làm cách nào để kết nối với MySQL bằng Sequelize?

js, đây là các bước để làm theo. .
Mở máy chủ web Express
Thêm dữ liệu cấu hình cho cơ sở dữ liệu MySQL hiện có
Mở một phần tiếp theo
Trong phần tiếp theo, hãy tạo một mô hình hướng dẫn
Viết bộ điều khiển
Xác định tất cả các tuyến để xử lý từng chức năng CRUD
mở người đưa thư
Kiểm tra API REST CRUD

Sự khác biệt giữa MySQL và Sequelize là gì?

MySQL có thể được phân loại là một công cụ trong danh mục "Cơ sở dữ liệu", trong khi Phần tiếp theo được nhóm trong "Trình ánh xạ quan hệ đối tượng (ORM)". "Sql" là lý do hàng đầu khiến hơn 778 nhà phát triển thích MySQL, trong khi hơn 17 nhà phát triển đề cập đến "ORM tốt cho nút

Phần tiếp theo có sử dụng MySQL2 không?

MySQL2 là thư viện trình kết nối MySQL được Sequelize sử dụng để kết nối với máy chủ db MySQL.