Sequelize - issue with foreign key in create include results in null value

When using the create include method, the foreign key is returning null, while the rest of the data is successfully saved from the passed object.

This is my transaction model setup:


module.exports = (sequelize, DataTypes) => {
    const Transaction = sequelize.define('transactions', {
        id: {
            type: DataTypes.INTEGER,
            allowNull: true,
            primaryKey: true
        },
        receiptNumber: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        supCustID: {
            type: DataTypes.INTEGER,
            allowNull: true
        },
        userID: {
            type: DataTypes.INTEGER,
            allowNull: true
        },
        type: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        status: {
            type: DataTypes.INTEGER,
            allowNull: true
        },
        remarks: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        createdAt: {
            type: 'TIMESTAMP',
            defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),
      allowNull: false
        },
        updatedAt: {
            type: 'TIMESTAMP',
            defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),
      allowNull: false
        }
    }, {
        tableName: 'transactions'
  });

  Transaction.associate = models => {
    Transaction.Order = Transaction.hasMany(models.Order, {
      as: 'Orders',
      foreignKey: 'transaction_id'
    })

    Transaction.SupCust = Transaction.belongsTo(models.SupCust, {
      as: 'SupCust',
      foreginKey: 'supCustID'
    })

    Transaction.User = Transaction.belongsTo(models.User, {
      as: 'User',
      foreginKey: 'userID'
    })
  }

  return Transaction;
};

Here is the Orders Model structure:

/* jshint indent: 1 */

module.exports = (sequelize, DataTypes) => {
    const Order = sequelize.define('orders', {
        id: {
            type: DataTypes.INTEGER,
            allowNull: true,
            primaryKey: true
        },
        transaction_id: {
            type: DataTypes.INTEGER,
            allowNull: true
        },
        itemID: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        qty: {
            type: DataTypes.INTEGER,
            allowNull: true
        },
        itemCost: {
            type: DataTypes.REAL,
            allowNull: true
        },
        discount: {
            type: DataTypes.REAL,
            allowNull: true
        },
        totalAmount: {
            type: DataTypes.REAL,
            allowNull: true
        }
    }, {
    tableName: 'orders',
    timestamps: false,
    hooks: {
      afterValidate: (Order) => {
        console.log(Order)
      },
    }
  });

  Order.associate = models => {
    Order.belongsTo(models.Transaction, {
      as: 'Transactions',
      foreignKey: 'transaction_id'
    })

    Order.belongsTo(models.ItemList, {
      as: 'Items',
      foreignKey: 'itemID'
    })
  }

  return Order;
};

The below code executes the insert data logic:

return await models.Transaction
    .findOne({ where: { id: values.id || -1 } })
    .then(async function (obj) {
        if(obj) { // update
          return await obj.update(values, {individualHooks: true});
        }
        else { // insert
          const {id, ...payload} = values
          return await models.Transaction.create(payload, {
            include: [{ 
              association: models.Transaction.Order 
            }], 
          });
        }
    })

Results obtained from the console:

Executing (default): INSERT INTO `transactions` (`id`,`receiptNumber`,`supCustID`,`userID`,`type`,`createdAt`,`updatedAt`) VALUES ($1,$2,$3,$4,$5,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP);

Executing (default): INSERT INTO `orders` (`id`,`transaction_id`,`itemID`,`qty`,`itemCost`) VALUES ($1,$2,$3,$4,$5);

Output from hooks on orders model displayed in the console log:

dataValues:
   { id: null,
     itemID: 1008,
     itemCost: '2',
     qty: '1',
     transaction_id: null },

I'm puzzled why this value is always null. Am I overlooking something?

Answer №1

My issue was resolved by incorporating the autoincrement feature into my transaction model.

id: {
     type: DataTypes.INTEGER,
     allowNull: true,
     primaryKey: true,
     autoIncrement: true
}

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

What is the process for transmitting information via a Link in Next.js?

In my upcoming 13.1.5 version, I am faced with a challenge of sending the value of contact.name through a Link in my component. I am looking for the most effective approach to achieve this. The initial code block for the Link represents my original code. ...

Implementing a custom button specifically for the month view in JavaScript FullCalendar

I have successfully added a custom button to my JavaScript full calendar code, but I would like this button to be displayed only in the month view. $(document).ready(function() { var calendar = $('#calendar').fullCalendar({ editable: tru ...

Navigating through various div elements in Javascript and sending parameters to a script

Context In my project, I am using PHP to generate a series of voting sections. Each section follows the same format except for a unique number assigned to it, which increases with each iteration of the PHP loop. To keep track of the unique numbers, I uti ...

Generating examples of two models that are interdependent

In my Javascript form, I have implemented an AJAX POST request that successfully creates a new instance of a model called Component. Now, my goal is to allow users to input keywords for the Component model through the same form. To achieve this, I have al ...

Why isn't my custom HTML attribute displaying correctly?

In my current React app project, I have been incorporating custom attributes to HTML tags and React components for End-to-End (E2E) tests using Testcafe. However, I am facing an issue where the additional data-test="burger-menu-btn" attribute is ...

A step-by-step guide on sending a fetch request to TinyURL

I have been attempting to send a post request using fetch to tinyURL in order to shorten a URL that is generated on my website. The following code shows how I am currently writing the script, however, it seems like it's not returning the shortened URL ...

Transform the API response array into a different format, ready to be passed as a prop to a

Looking to incorporate the Vue Flipbook component into my project, which requires an array of image URLs for the "pages" prop. I am fetching post responses from the WordPress REST API. My goal is to extract the "image" property from the response array and ...

Can you explain the functionality of $on.constructor in AngularJS?

Recently, I attempted an XSS challenge on the PortSwigger labs website. You can find the challenge here. This is my solution to the XSS challenge: {{$on.constructor('alert(1)')()}} However, since I have no prior experience with AngularJS, I&apo ...

Adaptive Images with jQuery Mobile Listview

I have been experimenting with the classic listview example featuring thumbnails from the jquery mobile documentation. However, when I upload images of different sizes, they do not display properly due to resolution issues. How can this be resolved? Here ...

Tips for utilizing Material UI's Tooltip feature alongside a TableRow

I'm currently facing an issue where I'm trying to include a MUI TableRow inside a Tooltip component in order to display a long uuid when hovering over the row. However, I noticed that all the columns of the row are being compressed into the first ...

Distinctive titles for JavaScript constructors/prototypes compared to classes

When working with JavaScript ES6, classes allow us to write code like this: class RectangularShape { constructor(height, width) { this.height = height; this.width = width; } getArea() { return this.height * this.width } static some ...

Trigger event upon variable modification

Currently, I am working on a school project that involves creating a website where users can listen to music together. I have implemented a button that allows the user to listen to the same song another user is currently playing at the right position. Howe ...

The module "jquery" in jspm, jQuery, TypeScript does not have a default export

Having some trouble setting up a web app with TypeScript and jspm & system.js for module loading. Progress is slow. After installing jspm and adding jQuery: jspm install jquery And the initial setup: <script src="jspm_packages/system.js"></scri ...

There seems to be an issue with the functionality of the JavaScript Quiz as it is

While working on my JS quiz, I encountered an issue where some answers were not displaying due to quotes and the need to escape HTML characters. Additionally, I am facing difficulty in accurately awarding points or deductions based on user responses. Curre ...

The return value of fs.mkdirSync is undefined

I'm facing a challenge with creating a directory and utilizing that directory as a variable to extract files from zip/rar files. The section of code that is causing an error is shown below: var fileZip = fileName.replace(/^.*[\\\/]/, ...

Executing AngularJS code that returns a promise within an event

In my run function, I am handling the $routeChangeSuccess event. My goal is to use $http to load some data and then change the $template. The issue here is that $http works asynchronously. I have attempted to return a promise inside the event, but it has ...

JavaScript: Understanding the concept of closure variables

I am currently working on an HTML/JavaScript program that involves running two counters. The issue I am facing is with the reset counter functionality. The 'initCounter' method initializes two counters with a given initial value. Pressing the &a ...

Steer clear of 405 errors by implementing AJAX in combination with Flask and JINJA templ

Hey there, I'm fairly new to backend work so please bear with me. I've been doing some research but haven't found the answer yet. Currently, I'm working on an application that fetches search results from a 3rd party API. I'm tryi ...

What is the best way to set up Flow type checking for functions passed as props in a React and Redux application?

In my app, I've been passing Redux action creators as props and want to improve type checking. Using the generic Function type has limitations, so I tried using the existential operator (*) in my Props type with no success in getting Flow to infer the ...

Hover over parts of an image to bring attention to them

I am interested in developing a webpage featuring a black and white image of 5 individuals. When hovering over each person, I would like them to illuminate and display relevant information in a dialog box next to them. Do you have any tips on how I can ac ...