Last active
November 26, 2019 01:04
-
-
Save jasheloper/ed2d0033561bf80e343a8ccc6f6fd9d5 to your computer and use it in GitHub Desktop.
Migrations - Creating 2 tables in the up function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.up = function(knex, Promise) { | |
return knex.schema | |
.createTable('farms', tbl => { | |
tbl.increments(); | |
tbl.string('farm_name', 128) | |
.notNullable(); | |
}) | |
// we can chain together createTable | |
.createTable('ranchers', tbl => { | |
tbl.increments(); | |
tbl.string('rancher_name', 128); | |
tbl.integer('farm_id') | |
// forces integer to be positive | |
.unsigned() | |
.notNullable() | |
.references('id') | |
// this table must exist already | |
.inTable('farms') | |
}) | |
}; | |
// Note that the foreign key can only be created after the reference table. | |
// In the down function, the opposite is true. We always want | |
// to drop a table with a foreign key before dropping the table it references. | |
exports.down = function(knex, Promise) { | |
// drop tables in opposite order | |
// than they were created (shoes & socks concept) | |
return knex.schema | |
.dropTableIfExists('ranchers') | |
.dropTableIfExists('farms') | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment