Using Knex to Generate a Migration Including a Foreign Key

I attempted to use the code from this link in order to create a foreign key:

how to do knex.js migration

However, an error occurred at this line of code:

table.bigInteger('AddressId')
    .unsigned()
    .index()
    .inTable('Address')
    .references('id');

The error message retrieved was as follows:

    TypeError: Object # has no method 'inTable' at 
     TableBuilder_MySQL._fn (/Users/lwang/knex/migrations/20150204161920_lei_maigration.js:15:56) at
     TableBuilder_MySQL.TableBuilder.toSQL (/Users/lwang/knex/node_modules/knex/lib/schema/tablebuilder.js:61:12) at 
     SchemaCompiler_MySQL.createTable (/Users/lwang/knex/node_modules/knex/lib/schema/compiler.js:14:53) at 
     SchemaCompiler_MySQL.SchemaCompiler.toSQL (/Users/lwang/knex/node_modules/knex/lib/schema/compiler.js:35:24) at 
     SchemaBuilder_MySQL.SchemaBuilder.toSQL (/Users/lwang/knex/node_modules/knex/lib/schema/builder.js:41:35) at 
     Runner_MySQL. (/Users/lwang/knex/node_modul...

Answer №1

Apologies for the delay, but the issue is due to:

table.bigInteger('AddressId')
    .unsigned()
    .index()
    .inTable('Address')
    .references('id');

The correct syntax should be:

table.bigInteger('AddressId')
    .unsigned()
    .index()
    .references('id')
    .inTable('Address');

The inTable function must come after calling references, as mentioned in the documentation

Sets the "table" where the foreign key column is located after calling column.references.

Answer №2

It seems there has been a recent update in how foreign keys are assigned.

Rather than the traditional method, I opted for a different approach:

table.integer('AddressId').unsigned()
tables.foreign('AddressId').references('Address.id');

This method worked smoothly for me.

For more information, you can refer to this GitHub gist: https://github.com/knex/knex/issues/245

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Restricting the length of dynamic dropdowns in a React application

Click here to view the code on CodeSandbox My dropdown menu options are dynamically generated and filtered based on custom data. const dropdownData = [ { code: "others", name: "Others", amenity: [] }, { code: "bed", name: "Bed", ...

Error occurs in console when using .getJSON with undefined JSON, but does not happen when using embedded data

Can someone help me understand why I'm getting an 'undefined' response when I use console.log(tooltipValues), but there's no issue with console.log(tooltipJSON). I've noticed that when I embed the data directly in my JS code, ever ...

Modify the indentation format in CSS/JS

When the Tab key is pressed in an HTML page and the tabbed link gets highlighted, is it feasible to customize the style of that highlight? ...

Schedule Master: A sophisticated tool for time management

I have been following the instructions to implement a date time picker from this tutorial. I downloaded the necessary js and css files and placed them in the respective directories. However, when I click on the calendar icon, the calendar does not pop up. ...

Converting SQL code to SQLAlchemy mappings

I have an unusual query that aims to retrieve all items from a parent table that do not have corresponding matches in its child table. If possible, I would like to convert this into an SQLAlchemy query. However, I am unsure of how to proceed as my experie ...

The property 'licenses' has incompatible types. The type 'License[]' cannot be assigned to type 'undefined' in the getServerSideProps function while using iron-session

I am encountering an issue with red squiggly lines appearing on the async keyword in my code: Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined ...

Contrast 2 GET objects retrieved from separate controllers

I have 2 collections of data from different controllers. Data Collection 1 (Controller Name): [{id:1,"name":"jakov"},...] Data Collection 2 (Controller Nickname): [{id:1, "nickname" : "jandric", "nameId" :1, "title" : "master"},...] I send data from C ...

Optimal method for implementing $scope.$apply(); or $scope in scenarios outside of Angular when working with Angular Components

As outlined in Kendo's best practices, there are instances where Kendo necessitates the use of $scope.$apply(); to update Angular. However, with the emergence of the new AngularJS 1.5 component, it is advised against relying on $scope. The code for t ...

Troubleshooting a JavaScript project involving arrays: Let it pour!

I'm a beginner here and currently enrolled in the Khan Academy programming course, focusing on Javascript. I've hit a roadblock with a project called "Make it rain," where the task is to create raindrops falling on a canvas and resetting back at ...

Please enter only numerical values using jQuery

Currently, I am facing a slight issue. My goal is to only run the code when the input characters are numbers. This is the snippet of code I have been working with: $(".jq-sales, .jq-variablecosts, .jq-fixedcosts, .jq-additional-sales, .jq-sales-units, .j ...

What is the best way to conceal a dropdown menu when the page first loads?

I have a dropdown menu that is displaying like this: <ul> <li class="dropdown open"> <a aria-expanded="true" href="#" class="dropdown-toggle waves-effect waves-button waves-classic" data-toggle="dropdown"> <spa ...

Display HTML content in autocomplete using jQuery UI

I implemented a search feature on my website using jQueryUI, similar to how it works on Facebook. Below is the jQuery code: //search main function split( val ) { return val.split( ); } function extractLast( term ) { return split( term ).pop(); } ...

Is there a way to store my collection data in a variable and access it externally from the file?

Topic of Interest : Working with Discord.js I am seeking advice on how to save collector data in a variable and access it outside of the file, for example in index.js. I aim to create a setup command that prompts users with questions when they type -setup ...

Streamlining all icons to a single downward rotation

I am currently managing a large table of "auditpoints", some of which are designated as "automated". When an auditpoint is automated, it is marked with a gear icon in the row. However, each row also receives two other icons: a pencil and a toggle button. W ...

Is there a way to dynamically update the target of a form using JavaScript?

My goal is to change the target of a form in order to open a new window. However, all redirections of this form use the same window except for one specific button. This button calls a custom JavaScript function that needs to change the default "_self" targ ...

Ways to maintain an array in Vuex even after mutations take place? (Specifically focusing on persisting data through browser refresh)

I am in the process of developing a basic shopping cart and I need guidance on how to persist an array containing cart data when executing the addProduct mutation below. Is there a way to save this data temporarily to prevent it from being lost due to br ...

Looking to integrate the date, month, and year selection tags into the inline format

The Edit User Profile page includes a Birthday field, which is currently displayed vertically. I am looking to change the layout so that the Birthday field appears horizontally. Here is the code I am using: Within visitors/edit.html.erb, <%= simple_f ...

The addition operation in JavaScript seems to be malfunctioning as it is not adding up my values

After encountering an issue with calculating the number of payments, I discovered that the addition operator was not functioning as expected. Instead of summing up values, it was treating them as strings. For instance, when trying to add 3 and 5, the out ...

WebRTC functions effectively within the same network, but encounters difficulty when communicating between different IP addresses

Please find my code on Github: https://github.com/rashadrussell/webrtc_experiment/blob/master/public/script.js I am currently working on developing a 1-to-1 video conferencing script using WebRTC. The script is hosted on AppFog, a cloud hosting platform. ...

When using getStaticPaths, an error is thrown stating "TypeError: segment.replace is not a function."

I am a beginner when it comes to using Next.js's getStaticPaths and I recently encountered an error that has left me feeling lost. Below is the code I have written (using query from serverless-mysql): export async function getStaticPaths() { cons ...