surajck surajck - 1 year ago 102
Javascript Question

Proper way to define two way relations between two tables

I have three tables:

Employee (emp_id,name)
Projects (pid,proj_status)
Project_Allocation (pid,emp_id)

To find the people belonging to my project:

1. I have my name, I query my emp_id.

2. Using my emp_id, I query (withRelated) for all my projects from Project_Allocation (completed ones as well) with a belongsTo relation defined on Projects

3. Then I pick the pid of the project having status as 'LIVE'

4. Now I pick all the models having this pid in Project_allocation.

The issue I'm encountering is when creating the schemas for Project and Project_Allocation tables. The both require each other and I cant load them both. Please suggest how I can rewrite this.

Here are few extracts:

The Project_Allocation file:

var Project = require('./project');
var PASchema = Bookshelf.Model.extend({
tableName: 'project_allocation',
project: function(){
return this.belongsTo(ProjectSchema, 'pid')

The Project file:

var ProjAlloc = require('./projAlloc');
var ProjectSchema = Bookshelf.Model.extend({
tableName: 'project',
idAttribute: 'pid',
allocatedIDs: function() {
return this.belongsTo(PASchema,'pid')

Answer Source

The problem was with require. The deadlock was being caused there. I was defining each of my table in a separate file and require-ing them in other table definitions (i.e other files). Writing all my table definitions in a single file and then exporting that object worked fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download