📅  最后修改于: 2023-12-03 15:19:59.600000             🧑  作者: Mango
Schema is an important concept in Knex.js, a query builder for Node.js, that helps you define and manage database tables and their relationships. In this guide, we'll dive into the basics of schema in Knex.js and how you can use it to create and modify your database's schema.
A schema is a way of organizing and describing the structure of a database. It defines the tables, columns, indexes, relationships, and constraints that make up the database's structure. In Knex.js, a schema consists of one or more table definitions and any associated constraints or indexes.
To create a table in Knex.js, you can use the knex.schema.createTable()
method:
knex.schema.createTable('users', function (table) {
table.increments('id')
table.string('name')
table.string('email').unique()
table.timestamps()
})
This will create a new table called users
with an auto-incrementing id
column, name
and email
columns, and timestamp columns for created_at
and updated_at
. You can add additional columns or modify the existing ones as needed.
You can also modify an existing table's schema using the knex.schema.table()
method:
knex.schema.table('users', function (table) {
table.boolean('active').defaultTo(false)
table.dropColumn('email')
})
This will add a new active
column to the users
table and remove the email
column. You can use any of the supported column types and modifiers in Knex.js to make additional modifications.
To drop a table in Knex.js, you can use the knex.schema.dropTableIfExists()
method:
knex.schema.dropTableIfExists('users')
This will delete the users
table if it exists. You can also add multiple table names to drop multiple tables at once.
In summary, schema in Knex.js is a way to define and manage the structure of your database tables. You can use the knex.schema
object to create, modify, and delete tables as needed. With this powerful tool, you can easily manage your database schema in a declarative way and ensure your database is always in the right state.