Is it possible to have nullable foreign keys using objectionjs/knex?

It seems like I'm facing a simple issue, but I can't quite figure out what mistake I'm making here.

I have a table that displays all the different states:

static get jsonSchema() {
    return {
      type: 'object',

      properties: {
        id: { type: 'integer' },
        name: { type: 'string', minLength: 1, maxLength: 100 },
      },
    }
  }

  static get relationMappings() {
    return {
      users: {
        relation: Model.HasManyRelation,
        modelClass: User,
        join: {
          from: `${tableNames.state}.id`,
          to: `${tableNames.user}.state_id`,
        },
      },
    }

Migration script for the state table:

await knex.schema.createTable(tableNames.state, (table) => {
    table.increments().primary().notNullable()
    table.string('name', 100).notNullable()

User table model definition:

static get jsonSchema() {
    return {
      type: 'object',

      properties: {
        id: { type: 'integer' },
        first_name: { type: 'string', minLength: 1, maxLength: 100 },
        last_name: { type: 'string', minLength: 1, maxLength: 100 },
        state_id: { type: 'integer', default: null },
      },
    }
  }

  static get relationMappings() {
    return {
      state: {
        relation: Model.BelongsToOneRelation,
        modelClass: State,
        join: {
          from: `${tableNames.user}.state_id`,
          to: `${tableNames.state}.id`,
        },
      }
    }
  }

User table migration script:

await knex.schema
    .createTable(tableNames.user, (table) => {
      table.increments().primary().notNullable()
      table.string('first_name', 100).notNullable()
      table.string('last_name', 100).notNullable()
      table.integer('state_id').unsigned()

      table
        .foreign('state_id')
        .references('id')
        .inTable(tableNames.state)
        .onDelete('SET NULL')
    })

The current problem: I am trying to make the state_id column nullable so not every user needs to have a state assigned. However, when I attempt to insert a user without specifying a state_id, I encounter this error:

insert or update on table \"user\" violates foreign key constraint \"user_state_id_foreign\"
.

Answer №1

here are a couple of mistakes you might be making

  1. when defining your column in the json schema, use
    state_id: {type: ['integer', 'null']}
  2. in your user migrations, ensure that you have
    table.integer('state_id').unsigned().nullable()

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

Passing a service into a directive results in an undefined value

Can someone help me understand why a service I am injecting into a directive is returning undefined in certain instances? If you would like to take a look at the code, here is a plunker link: https://plnkr.co/edit/H2x2z8ZW083NndFhiBvF?p=preview var app = ...

I'm facing an issue with SSRProvider in my NextJs application

My application is developed using NextJs and Typescript, utilizing the react-bootstrap library for creating components. I am facing an issue where I keep receiving an error message stating that When server rendering, you must wrap your application in an &l ...

What is the best way to choose a single item from an array using jQuery?

Within an array, I have IDs and descriptions like: var tablica = [{"3":"asdasd asd"},{"19":"asddas fff"},{"111111":"adas asf asdff ff"},{"4":"re"},{"5":"asdasd"},{"6":"we"},{"7":"asdasdgg"},{"9":"asdasdasd"},{"16":"sdads"},{"10":"asdgg"},{"11":"ggg"}]; ...

JavaScript - Reveal a div when a grid item is clicked

I have created a grid with a 5x7 layout using divs. I am trying to achieve a feature similar to the Netflix interface where, upon clicking on a div, a larger div will appear beneath it. This larger div should expand to 100% width of the parent container, p ...

Tips on initiating a $http.get request every second using a service

I am working on an angular application that includes a $http.get request. While it currently functions properly, I need it to be executed every second in order to retrieve new data. Service: angular.module('adf.widget.liveCharts') .service(&a ...

When I attempt to execute 'npm run build' or 'npm run start', a component is missing classes. However, despite my efforts, others are unable to replicate the error

Check out the repository here. This is essentially the example provided by Material-UI with an additional input component in pages/index.tsx After running npm run build and npm run start on both my local machine and VPS, the outlined input component disp ...

Setting up popover functionality in TypeScript with Bootstrap 4

Seeking assistance with initializing popovers using TypeScript. I am attempting to initialize each element with the data-toggle="popover" attribute found on the page using querySelectorAll(). Here is an example of what I have tried so far: export class P ...

NodeJs error: 'messages is not a function'

Getting Error: messages is not a function Why does != messages('message',locals) show an error? Even though it seems correct. Please assist me in identifying the error. Thank you! app.js app.use(require('connect-flash')()); app.us ...

Using jQuery's append function will retrieve external source files within script tags, however, it will not officially render them in the DOM

After including a script with an external source and attempting to parse it using jQuery, the script is downloaded but not loaded into the DOM. This issue persists regardless of which jQuery DOM insertion method I use, such as .append(). Take a look at th ...

Verify the validation of the text box

Checking a textbox control for validation is necessary. Validation Criteria: Value should be between 0 and 1000, with up to 2 decimal places (e.g. 1.00, 85.23, 1000.00). Once 2 decimal points are used, users should not be able to enter additional ze ...

The Mantine date picker is causing an error stating that objects are not valid as a React child

I'm currently experimenting with utilizing Mantine Date in NextJS. The goal is to have the selected date displayed in the HTML text heading when a user clicks on it. For instance, if a user selects January 1st, 2023, the text should show like this: Da ...

One simple click to auto-fill the form

I have encountered a problem that has been discussed before, but my lack of coding knowledge is making it difficult for me to find a suitable solution that matches the code on my website. The issue at hand is as follows: I need my form to populate car mak ...

The functionality of JQuery's .hover() is disabled once an HTML onClick() event is activated

I am currently working on a webpage and attempting to incorporate JQuery into it for the first time. However, I seem to be encountering some issues that I believe might have simple solutions. Background Information My JQuery code only contains one event l ...

phpif (the current date is after a certain specific date, do

Can someone please help me solve this problem? I want to prevent echoing a variable if the date has already expired. Currently, my PHP code displays: Match 1 - April 1, 2015 Match 2 - April 8, 2015 What I need is for Match 1 to not be echoed if the cur ...

Registration process in Node Express application encounters persistent loading when accessed through Postman

I've been working on a signup model for user accounts in Node.js, but when testing it in Postman, I encountered an issue where there was no response or failure. This left me stuck and I received the following error message in my terminal: Unhandled ...

Developing a dynamic web application using the Django framework along with the Vue.js library and Highcharts for

I am currently working on a data visualization web app using Django, Highcharts, and JQuery. I have recently transitioned from JQuery to Vue JS and I am struggling with fetching JSON data from a specific URL. Below is the code snippet: Template <!doc ...

Steps to create a hover effect that alters the appearance of another chosen "element"

For instance, I have two classes named A and B. I want to be able to change the appearance of B when I hover over it, such as its color or size. I am unsure if this can be achieved using CSS and the onmouseover event. I am including a snippet of code that ...

Tips for invoking a url with JavaScript and retrieving the response back to JavaScript

I am trying to make a URL call from JavaScript with a single parameter, and the URL should respond to that specific request. Here is an example of the response format: {"success":true, "result": {"token":"4fc5ef2bd77a3","serverTime":1338371883,"expireT ...

PHP response is blank when password_hash or password_verify functions are used

My application utilizes JavaScript to retrieve a string and send it via POST to a PHP file on the server for processing. The PHP receiver is responsible for parsing the string, performing tasks, and sending back status updates to JavaScript. However, after ...

Using Swig template to evaluate a condition

I'm trying to achieve something similar using swig-template. var remId = $(this).attr('remId'); if (remId) { var end = remId.search('_'); var underscore = remId.slice(end, end + 1); var Id = remId.slice(end + 1, remId ...