- vừa được xem lúc

Sequelize : javascript ORM cho Node.js

0 0 7

Người đăng: Nguyen Van Truong

Theo Viblo Asia

Sequelize là một ORM dành cho Node.js và io.js. Nó hỗ trợ bạn truy cập một cách dễ dàng đến PostgreSQL, MySQL, MariaDB, SQLite và MSSQL cùng với các tính năng như là relations, transaction, replication ...

I. Cài đặt Sequelize.

  1. Cài đặt npm:
 sudo apt-get install npm
  1. Cài đặt Sequelize
 npm install --save sequelize
 Cài đặt hệ quản trị cơ sở dữ liệu mà bạn muốn tương tác, Sequelize hỗ trợ PostgreSQL, MySQL, SQLite và MSSQL:
 npm install --save pg pg-hstore npm install --save mysql // For both mysql and mariadb dialects npm install --save sqlite3 npm install --save tedious // MSSQL
  1. Tạo connection pool

Sequelize sẽ tạo 1 connection pool khi được khởi tạo vì vậy bạn chỉ nên tạo duy nhất 1 instance trên 1 database:

 var sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: 'mysql'|'mariadb'|'sqlite'|'postgres'|'mssql', pool: { max: 5, min: 0, idle: 10000 }, storage: 'path/to/database.sqlite' // Chỉ dùng khi MS là SQLite });

Bạn có thể connect trực tiếp đến 1 database uri như sau:

 var sequelize = new Sequelize('postgres://user:_@.com:5432/dbname');

II. Tính năng chính

  1. Model

Để tạo 1 ánh xạ giữa 1 model và 1 table ta sử dụng phương thức define. Sequelize sẽ tự động tạo các attributes là createdAt và updatedAt (nếu bạn không muốn sử dụng hoặc chỉ sử dụng 1 trong 2 attributes thì có thể tham khảo ở phần config sau đây).

 var Project = sequelize.define('Project', { title: Sequelize.STRING, description: Sequelize.TEXT })

Ngoài ra bạn có thể thêm các option cho các attributes:

 var Book = sequelize.define('Book', { title: { type: Sequelize.STRING, allowNull: false, defaultValue: true}, author: { type: Sequelize.STRING, allowNull: false}, ISBN: {type: Sequelize.STRING, unique: true}, });

Một số kiểu dữ liệu phổ biến của Sequelize:

 Sequelize.STRING // VARCHAR(255) Sequelize.STRING(1234) // VARCHAR(1234) Sequelize.STRING.BINARY // VARCHAR BINARY Sequelize.TEXT // TEXT Sequelize.INTEGER // INTEGER Sequelize.BIGINT // BIGINT Sequelize.BIGINT(11) // BIGINT(11) Sequelize.FLOAT // FLOAT Sequelize.FLOAT(11) // FLOAT(11) Sequelize.FLOAT(11, 12) // FLOAT(11,12) Sequelize.REAL // REAL Chỉ hỗ trợ PostgreSQL. Sequelize.REAL(11) // REAL(11) Chỉ hỗ trợ PostgreSQL. Sequelize.REAL(11, 12) // REAL(11,12) Chỉ hỗ trợ PostgreSQL. Sequelize.DOUBLE // DOUBLE Sequelize.DOUBLE(11) // DOUBLE(11) Sequelize.DOUBLE(11, 12) // DOUBLE(11,12) Sequelize.DECIMAL // DECIMAL Sequelize.DECIMAL(10, 2) // DECIMAL(10,2) Sequelize.DATE // DATETIME for mysql / sqlite, TIMESTAMP WITH TIME ZONE for postgres Sequelize.BOOLEAN // TINYINT(1) Sequelize.ENUM('value 1', 'value 2') Sequelize.ARRAY(Sequelize.TEXT) // Chỉ hỗ trợ PostgreSQL. Sequelize.JSON // JSON column. Chỉ hỗ trợ PostgreSQL. Sequelize.JSONB // JSONB column. Chỉ hỗ trợ PostgreSQL.

Bạn có thể xem tất cả các kiểu dữ liệu ở đường link sau http://docs.sequelizejs.com/en/latest/api/datatypes/

Config

 var Bar = sequelize.define('Bar', { /* bla */ }, { // Không tự động thêm timestamp attributes (updatedAt, createdAt) timestamps: false, // softDelete, Sequelize sẽ tự động thêm attribute deletedAt, chỉ hoạt động khi bạn enable timestamps paranoid: true, // Sử dụng underscore style thay cho camel style // updatedAt sẽ là updated_at... underscored: true, // chỉ định tên table tableName: 'my_very_custom_table_name' })

Sử dụng model:

 // Tạo model var Task = sequelize.define('Task', { title: Sequelize.STRING, rating: { type: Sequelize.INTEGER, defaultValue: 3 } })
 // Tìm kiếm // Tìm kiếm theo Id var task = Task.findById(123); // Tìm kiếm theo attributes var task = Task.findOne({ where: {title: 'aTask'} }).then(function(task) { }) var task = Task.findOne({ where: {title: 'aProject'}, attributes: ['id', ['title', 'rating']] }).then(function(task) { }) // Tìm kiếm nhiều bản ghi var task = Task.findAll().then(function(tasks) { }) // Giới hạn số lượng kết quả của query var task = Task.findAll({ limit: 10 }) // Bỏ qua 10 kết quả đầu tiên var task = Task.findAll({ offset: 10 }) //Đếm số lượng result var task = Task.count().then(function(c) { console.log("There are " + c + " tasks!") })
 // Thêm, Sửa, Xóa // Thêm mới // 1. Tạo một thể hiện của model (chưa được lưu vào database) var task = Task.build({ title: 'specify the project idea', rating: 2 }) task.title // ==> 'specify the project idea' task.rating // ==> 2 // Để lưu vào database chúng ta sử dụng function save task.save() // 2.Tạo bản ghi trong database Task.create({ title: 'foo', rating: 5}); // Sửa // Có 2 cách để để cập nhật dữ liệu // Cách 1: task.title = 'a very different title now' task.save().then(function() {}) // Cách 2 task.update({ title: 'a very different title now' }).then(function() {}) // Xóa task.destroy({ force: true })
  1. Query

    • Để select một vài attribute, bạn có thể sử dụng attributes optin
 Model.findAll({ attributes: ['foo', 'bar'] }); // => SELECT foo, bar from ...
  • Mệnh đề where
 Post.findAll({ where: { authorId: 2 } }); // SELECT * FROM post WHERE authorId = 2 Post.findAll({ where: { authorId: 12, status: 'active' } }); // SELECT * FROM post WHERE authorId = 12 AND status = 'active'; Post.destroy({ where: { status: 'inactive' } }); // DELETE FROM post WHERE status = 'inactive'; Post.update({ updatedAt: null, }, { where: { deletedAt: { $ne: null } } });
  • Các toán tử bạn có thể sử dụng cùng với where
 $and: {a: 5} // AND (a = 5) $or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6) $gt: 6, // > 6 $gte: 6, // >= 6 $lt: 10, // < 10 $lte: 10, // <= 10 $ne: 20, // != 20 $between: [6, 10], // BETWEEN 6 AND 10 $notBetween: [11, 15], // NOT BETWEEN 11 AND 15 $in: [1, 2], // IN [1, 2] $notIn: [1, 2], // NOT IN [1, 2] $like: '%hat', // LIKE '%hat' $notLike: '%hat' // NOT LIKE '%hat' $iLike: '%hat' // ILIKE '%hat' (Phân biệt hoa thường) (chỉ hộ trợ PG) $notILike: '%hat' // NOT ILIKE '%hat' (chỉ hộ trợ PG) $like: { $any: ['cat', 'hat']} // LIKE ANY ARRAY['cat', 'hat'] $overlap: [1, 2] // && [1, 2] (PG array overlap ) $contains: [1, 2] // @> [1, 2] (PG array contains ) $contained: [1, 2] // <@ [1, 2] (PG array contained ) $any: [2,3] // ANY ARRAY[2, 3]::INTEGER (chỉ hộ trợ PG)
  • Raw Query: Đôi khi bạn muốn excute một raw query, khi đó bạn có thể sử dụng sequelize.query
 sequelize.query("SELECT * FROM `users`");
  1. Relations

    Các loại relation gồm: One-To-One associations, One-To-Many associations, Belongs-To-Many associations

    3.1 One-To-One associations

    • BelongsTo:
 var Player = this.sequelize.define('Player', {/* attributes */}) , Team = this.sequelize.define('Team', {/* attributes */}); Player.belongsTo(Team);
- HasOne:
 var User = sequelize.define('User', {/* ... */}) var Project = sequelize.define('Project', {/* ... */}) // One-way associations Project.hasOne(User)

3.2 One-To-Many associations

 var User = sequelize.define('User', {/* ... */}) var Project = sequelize.define('Project', {/* ... */}) Project.hasMany(User, {as: 'Workers'})

3.3 Belongs-To-Many associations

 Project.belongsToMany(User, {through: 'UserProject'}); User.belongsToMany(Project, {through: 'UserProject'});
  1. Migration

    Để sử dụng tính năng migration bạn cần cài thêm package sequelize-cli

 $ npm install --save sequelize-cli
Các command của sequelize-cli
 $ sequelize db:migrate // Chạy migration. $ sequelize db:migrate:undo // Rollback lần cuối chạy migration. $ sequelize help // Hiển thị help. $ sequelize init // Khởi tạo project. $ sequelize migration:create // Tạo 1 migration mới. $ sequelize version
Bằng cách sử dụng queryInterfacebanh có thể sử dụng được hầu hiết các funtion
 //Tạo mới 1 table queryInterface.createTable( 'nameOfTheNewTable', { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, createdAt: { type: Sequelize.DATE }, updatedAt: { type: Sequelize.DATE }, attr1: Sequelize.STRING, attr2: Sequelize.INTEGER, attr3: { type: Sequelize.BOOLEAN, defaultValue: false, allowNull: false } }, { engine: 'MYISAM', // default: 'InnoDB' charset: 'latin1' // default: null } ) //Xóa 1 Table queryInterface.dropTable('nameOfTheExistingTable') //Xóa tất cả các Table queryInterface.dropAllTables() //Đổi tên table queryInterface.renameTable('Person', 'User') //Hiện thị tất cả các table showAllTables(options) //Thêm cột mới queryInterface.addColumn( 'nameOfAnExistingTable', 'nameOfTheNewAttribute', Sequelize.STRING ) // or queryInterface.addColumn( 'nameOfAnExistingTable', 'nameOfTheNewAttribute', { type: Sequelize.STRING, allowNull: false } ) //Xóa 1 cột queryInterface.removeColumn('Person', 'signature') //Đổi tên cột queryInterface.renameColumn('Person', 'signature', 'sig') //Thêm index queryInterface.addIndex( 'Person', ['firstname', 'lastname'], { indexName: 'SuperDuperIndex', indicesType: 'UNIQUE' } ) //Xóa index queryInterface.removeIndex('Person', 'SuperDuperIndex')

Tổng kết: Qua bài viết này mình muốn giới thiệu những tính năng cơ bản của Sequelize, Ngoài ra những tính năng trên còn có rất nhiều tính năng khác như: Transaction, Scope, Hooks...

Tài liệu tham khảo: - Sequelize Doc : http://docs.sequelizejs.com/

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 502

- vừa được xem lúc

Cài đặt WSL / WSL2 trên Windows 10 để code như trên Ubuntu

Sau vài ba năm mình chuyển qua code trên Ubuntu thì thật không thể phủ nhận rằng mình đã yêu em nó. Cá nhân mình sử dụng Ubuntu để code web thì thật là tuyệt vời.

0 0 376

- vừa được xem lúc

Đặt tên commit message sao cho "tình nghĩa anh em chắc chắn bền lâu"????

. Lời mở đầu. .

1 1 701

- vừa được xem lúc

Tìm hiểu về Resource Controller trong Laravel

Giới thiệu. Trong laravel, việc sử dụng các route post, get, group để gọi đến 1 action của Controller đã là quá quen đối với các bạn sử dụng framework này.

0 0 335

- vừa được xem lúc

Phân quyền đơn giản với package Laravel permission

Như các bạn đã biết, phân quyền trong một ứng dụng là một phần không thể thiếu trong việc phát triển phần mềm, dù đó là ứng dụng web hay là mobile. Vậy nên, hôm nay mình sẽ giới thiệu một package có thể giúp các bạn phân quyền nhanh và đơn giản trong một website được viết bằng PHP với framework là L

0 0 421

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 414