Tuesday, 4 April 2017

Creating Primary and Foreign Key relations in Sequelize

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



via Akshay Venugopal

No comments:

Post a Comment