KnexJS
Xem tutorial: https://www.youtube.com/watch?v=4nP6zFEvF_c
Cài Knex để kết nối db
npm i --save knex
Cài Knex global để tạo migrations và seeds
npm i -g knex
Cấu trúc thư mục
- db
|- migrations
|- seeds
|_ knex.js
- knexfile.js
Tạo knexfile.js ở thư mục ngoài cùng
module.exports = {
development: {
client: 'pg',
connection: {
host : '127.0.0.1',
port: 5433,
user : 'postgres',
password : 'abc',
database : 'exchanges'
},
migrations: {
directory: __dirname + '/db/migrations'
},
seeds: {
directory: __dirname + '/db/seeds'
}
},
production: {
}
}
Tạo Migrations
Tạo migrations bảng users và todos (Chạy xong sẽ có file trong thư mục: migrations)
knex migrate:make create_users_and_todos_tables
File trong migrations vừa tạo dùng để tạo table, cú pháp như sau (Code dưới là tạo 2 bảng):
exports.up = function(knex, Promise) {
return knex.schema
.createTable('users', (table) => {
table.increments();
table.string('name').notNullable()
table.string('email').notNullable()
table.timestamp('created_at').defaultTo(knex.fn.now())
table.timestamp('updated_at').defaultTo(knex.fn.now())
})
.createTable('todos', (table) => {
table.increments();
table.timestamp('created_at').defaultTo(knex.fn.now())
table.timestamp('updated_at').defaultTo(knex.fn.now())
table.string('title').notNullable()
table.integer('user_id').references('id').inTable('users')
})
};
exports.down = function(knex, Promise) {
return knex.schema.dropTable('todos').dropTable('users')
};
Khi tạo xong thì dùng từng lệnh sau để chương trình tự chạy file trong migrations
knex migrate:rollback
knex migrate:latest
Chạy với môi trường khác
knex migrate:latest --env production
Tạo Seeds
Tạo seeds để insert dữ liệu (đặt tên 01_users.js, 02_todos.js,.. để insert theo thứ tự)
Cú pháp:
knex seed:make 01_users
Chạy tất cả file trong thư mục Seeds:
knex seed:run