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 alternative can be used for jquery isotope when JavaScript is not enabled?

Is there a backup plan for jQuery isotope if JavaScript isn't working? For instance, if I'm using the fitColumns feature, is there an alternative layout style available in case JavaScript is disabled, similar to what is seen on the new Myspace? ...

Transforming Yii1 code into Yii2 code (altering the language component)

I am facing an issue. I have a code in Yii1 that allows me to change the language on my site. echo CHtml::ajaxLink('EN', array('/'), array( 'type' => 'POST', 'success' => 'j ...

IE encountered an invalid character

While working on a JavaScript function, I encountered an issue with a string variable. Specifically, when running the page in IE with this script, I receive an error message indicating an invalid character at the following line: let displayString = `${s ...

Animating Text Changes with JavaScript and jQuery

In my HTML, I have an input type="text" element and I want to attach an event handler that triggers when the text is changed. The issue arises because this input's value is dynamically updated by another JavaScript function, causing the event handler ...

Updating the footer of a React application using Material UI Grid

Having some trouble customizing the footer in a React Material-UI grid. Refer to the image below for details. Any ideas on how to change the: 1 row selected? Thank you! ...

Sending a file using Angular's $http service

I am facing an issue while trying to upload a form with an image file using the angular $http function and multer in the background for receiving. I have successfully uploaded the image via a direct form submission (without angular) as shown below: <fo ...

Address NPM vulnerabilities through manual fixes

I downloaded a repository and ran an npm install, but encountered an error at the end. Now, every time I run npm audit, I receive the following message: found 18 vulnerabilities (5 low, 12 moderate, 1 high) in 15548 scanned packages 9 vulnerabilities requ ...

The JavaScript error occurred: TypeError - Unable to access the property 'map' as it is undefined

import Link from 'next/link' export const getStaticProps = async () => { const res = await fetch('https://jsonplaceholder.typicode.com/users'); const data = await res.json(); return { props: { ninjas: data } } } const ...

delivering axios response to display the page

I have a code snippet that requests data from an external API using axios and I want to incorporate the response into my rendered page. Here is my code: //Snippet from my controller required in main routes exports.recordBySlug = async (req, res, next) =&g ...

What is the process for transforming a method into a computed property?

Good day, I created a calendar and now I am attempting to showcase events from a JSON file. I understand that in order to display a list with certain conditions, I need to utilize a computed property. However, I am facing difficulties passing parameters to ...

`Express 4 with beautiful locals.pretty`

Is there a way to send nicely formatted HTML using Express 4? I need to know how to properly use app.locals.pretty with Express 4. The old syntax doesn't seem to be working: app.locals.pretty = true; Here is the full code block: app.set('port& ...

Using Node to upload various large JSON files into mongoDB

Currently, I am dealing with the task of parsing numerous large JSON files into my mongoDB database. To accomplish this, I have been utilizing the stream-json npm package. The process involves loading one file at a time, then manually changing the filename ...

Determining when a text area has selected text without constant checking

class MarkdownEditor extends React.Component { constructor(props) { super(props); this.timer = null; this.startIndex = null; this.endIndex = null; } componentDidMount() { this.timer = setInterval(() => { this.setSelectio ...

Issues with Contenteditable functionality in JavaScript

My goal is to make a row editable when a button is clicked. $(":button").click(function(){ var tdvar=$(this).parent('tr').find('td'); $.each(tdvar,function(){ $(this).prop('contenteditable',true); }); }); <s ...

Is there a way to acquire and set up a JS-file (excluding NPM package) directly through an NPM URL?

Is it feasible to include the URL for the "checkout.js" JavaScript file in the package.json file, rather than directly adding it to the Index.html? Please note that this is a standalone JavaScript file and not an NPM package. The purpose behind this appr ...

What is the reason for typescript's lack of a "function" type?

As a newcomer to TypeScript, I'm puzzled as to why I am unable to define an object like this: const obj: { property1: string property2: boolean property3: function } It seems that the only workaround is to use: const obj: { property1: strin ...

Lack of y data in the Highcharts

I am facing an issue with retrieving yAxis data in Highcharts. You can view the fiddle at https://jsfiddle.net/LLExL/6496/. I have loaded Highcharts using the code below. $(function () { $('#RankingReportsHistory').highcharts( ...

The route parameters seem to be malfunctioning when using the Google Maps Directions API

Currently, I am attempting to transfer the latitude and longitude of a location from one HTML file to another using the $routeParams feature. In the second HTML file, I utilized the Google Maps directions API to display the directions from the source lati ...

What is the best way to customize the CSS of the Skype contact me button?

I am struggling with customizing the Skype contact me button. The standard Skype button has a margin of 24px and vertical-align set to -30px. I have tried removing these styles but have had no success. Here is the code snippet I am working with: Skype ...

Clone a specific link within a div using jQuery only one time

I have a group of divs and I want to copy the link from the first div and put it into the last div (mobile-link). Currently, it is either duplicating all the links and inserting them all at once, or if I use :eq(0), it's placing the first link in each ...