Relations between tables in Knex
I need another table ft_tickets, but in this case the table has a field called type_id which is related to the ft_ticket_types.
Since I already know how to write a migration it should be easy.
1 | exports.up = (knex, Promise) => { |
Great, a couple of two things here:
- What about the relationship 🤔. Knex can’t guess the field type_id is related to other table.
- The *timestamps method will generate automatically two extra fields for my table: created_at, updated_at.
Foreign Key in Knex
Creating FK using knex is easy as everything in Knex is. As I thought, there is a method who allows me to do that.
1 | table |
So first I define the field who will have the FK relation. Then I call the foreign function and pass as a parameter the name of the field. Now I need to call the references function which need as a parameter the name of the field of the source table, in this case is the ID. Last - but not least - using the inTable function I can tell to knex the table who contains the referenced field.
Running Migrations
1 | npx knex migrate:latest |
Return the message
1 | Batch 2 run: 1 migrations |
To the adminer cave!
Another great day thanks to knex