Creating Primary and Foreign Key relations in Sequelize

Akshay Venugopal

I have 2 models Project model and Task model defined in sequelize as shown below

import { INTEGER, STRING, DATE } from 'sequelize';
import sequelize from '../sequelize';
import Task from './task.model'

const ProjectModel = sequelize.define('project', {
    project_id: {
        type: INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    phabricator_project_id: {
        type: STRING,
        allowNull: false
    },
    name: {
        type: STRING
    },
    description: {
        type: STRING
    },
    start_date: {
        type: STRING,
    },
    end_date: {
        type: STRING
    }
},
    {
        timestamps: false
    }
);

export default ProjectModel;

and the task model

import { INTEGER, STRING, DATE } from 'sequelize';
import sequelize from '../sequelize';

const TaskModel = sequelize.define('task', {
    task_id: {
        type: INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    title: {
        type: STRING
    },
    status: {
        type: STRING
    },
    priority: {
        type: STRING
    },
    description: {
        type: STRING
    },
    tool_project_id: {
        type: STRING
    },        
    date_modified: {
        type: STRING
    }
},
    {
        timestamps: false
    }
);

export default TaskModel;

What I want to achieve is to create a relation between tool_project_id in TaskModel and phabricator_project_id in ProjectModel (they are same values only diff column names are given) and write a query for a GET request which outputs the data in form shown below

{ {project1Details,TaskDetails-->{task1, task2, task3}, {project2Details,TaskDetails-->{task4, task5, task6}, {project3Details,TaskDetails-->{task7, task8, task9}, {project4Details,TaskDetails-->{task10, task11, task12} }

All the database design has been done accordingly and another file is called to create all these databases. This is written in typescript and I tried this as a GET method

listByProjects(req, res) {
      TaskModel.belongsTo(ProjectModel, { as: 'task' , foreignKey: 'tool_project_id'});  
      ProjectModel.findAll({
          include:[{model:TaskModel}],
          where:{status:'open'}
        }).then(function(projects) {
            res.json(projects);
        });
    }

Here in this method I define the relation and try to list all 'open' tasks and send them back as response but I am getting the error

Unhandled rejection Error: task is not associated to project!

ANY HELP TO THIS PROBLEM WOULD BE WONDERFULL

Akshay Venugopal

The answer to this question is that when creating the table we should create the relation and then create the table such as

Create the relation also the name of the key should be same so as to create relation.

 TaskModel.belongsTo(ProjectModel, {foreignKey: 'project_id' });
 ProjectModel.hasMany(TaskModel, { foreignKey: 'project_id' });

Then create the table project and then tasks

 ProjectModel.sync({ force: false }).then(function () {
    console.log('Project table created');
    TaskModel.sync({ force: false }).then(function () {
        console.log('Task table created');
    });
});

then in the API method, you are invoking just include the model which you want to provide to get the required data.

 ProjectModel.findAll({
        include: [{
            model: TimeSheetModel,
            where: {
                status: "ACTIVE"
            },
        }],
  }).then(function (projects) {
        const responseData = {
            'status': 1,
            'message': 'List successfull.',
            'projects': projects,
        };
        res.json(responseData);
    }).catch(error => {
        const responseData = {
            'status': 1,
            'message': error.message,
            'projects': [],
        };
        res.json(responseData);
})

This uses nodemon and sequilize to manage node and relations of the table respectively

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Sequelize relations foreign key constraint

Sequelize foreign key reference composite primary key

Sequelize, foreign keys as composite primary key

Sequelize belongsToMany self reference not creating foreign key

R renaming rows and creating primary and foreign key

Django Foreign Key Relations

Paginating foreign key relations

fliped foreign key relations?

Sequelize wrong foreign key name when creating tables

Foreign key as primary key?

Hibernate interprets two foreign key relations as composite primary key(MappingException). Why?

How can I view the table relations in PostgreSQL (if there is a foreign key column, what the primary key is...)?

SQL: creating tables with primary keys and foreign key refering (

Foreign Key in Sequelize

MySQL: Creating a table that with a foreign key that references a primary key made up of foreign keys

List problems in foreign key relations

Primary Key and Foreign Key on Laravel

foreign key is not equal to primary key

Composite foreign key as primary key

Foreign Key to Primary key relation

Replacing a foreign key by a primary key

Find foreign key by primary key?

EF Core one-to-many-relations: Sets wanted foreign key into the same column of the primary key and thus no seeding is possible

graphql with sequelize join foreign key

Sequelize referencing to wrong foreign key

Foreign Key definitions on Sequelize Models

Foreign Key with Sequelize not working as expected

Sequelize associations not generating foreign key

Sequelize association with one foreign key