2016-10-07 5 views
1

だから私は(そうでない愚かな複雑な音)RolesInvestigatorsを持ってProjectsを持っているとBudgetPeriodRoleとしてEffortをコミットします。これを検索するのに実際にどのようなキーワードが適切かわかりません。ので、ここで行く:フェッチネストされたBelongsToMany協会

const Project = seq.define('Project', {/*...*/}); 
const Investigator = seq.define('Investigator', {/*...*/}); 
const BudgetPeriod = seq.define('BudgetPeriod', {/*...*/}); 
const Role = seq.define('Role', { 
    id:   { 
    type:   DataTypes.INTEGER, 
    primaryKey: true, 
    autoIncrement: true 
    }, 
    role:   { 
    type:  DataTypes.ENUM, 
    /*...*/ 
    }, 
    /*... Other role related info...*/ 
}); 
const Effort = seq.define('Effort', { 
    id:   { 
    type:   DataTypes.INTEGER, 
    primaryKey: true, 
    autoIncrement: true 
    }, 
    budgetedAY: { 
    type:   DataTypes.INTEGER, 
    allowNull: false, 
    defaultValue: 0 
    }, 
    /*... other effort related info...*/ 
}); 

さて、今の関係:私のクエリで

// Each Project can have many budget periods, BP knows its Project 
Project.hasMany(BudgetPeriod, {as: 'budgetPeriods'}); 

// Each Project has many Investigators, which have a Role on Many projects 
Project.belongsToMany(Investigator, {as: 'investigators', through: db.Role}); 

// Each Investigator, in their role, commits Effort toward the Projects during a BudgetPeriod 
Role.belongsToMany(BudgetPeriod, {as: 'effort', through: db.Effort}); 

私はプロジェクトを取得し、その関連BudgetPeriodsおよび研究者/役割を取得しています。 私は、リレーショナル・モデルRolesと関連しており、RoleProjectが続行に従って直接関連付けられていないため、取得方法を知りません。

Project.findById(projectId, { 
    include: [ 
    {model: Investigator, as: 'investigators'}, 
    {model: BudgetPeriod, as: 'budgetPeriods'}, 
    ], 
    order: [ 
    [{model: BudgetPeriod, as: 'budgetPeriods'}, 'period', 'ASC'] 
    ] 
}).then(res => console.log(res)) 

// Produces something like 
{ 
    budgetPeriods: [/*...*/], 
    investigators: [ 
    { 
     id:1, 
     name:'abc', 
     Role: { 
     id: 1, 
     role: 'PI' 
     } 
    } 
    ] 
} 

私はこのクエリで努力を取得する方法がわかりません。私は{model: Investigator, as: 'investigators', include: [{model: Effort, as: 'effort'}]},と、他の変形に{model: Investigator, as: 'investigators'},を変えてみました。私はまた、ルートinclude{model: BudgetPeriod, as: 'effort'}およびその他のバリエーションを入れてみましたが、私は別のリレーショナルモデルを通じて、リレーショナルモデルにモデルを関連付ける必要があるため、私これらBudgetPeriod (effort) is not associated to Investigator!

これはとても奇妙である理由のようなメッセージ内のすべての結果があります。

ご協力いただきありがとうございます。

答えて

0

私はこれに対する答えがあるとは思わないので、私はデータベース関係をリファクタリングしました。似たような問題を抱えている人には、私の変更があります。

データベース定義:変更なし

データベース関係:

Project.hasMany(BudgetPeriod, {as: 'budgetPeriods'}); 
Project.belongsToMany(Investigator, {as: 'investigators', through: db.Role}); 
Investigator.belongsToMany(BudgetPeriod, {as: 'effort', through: db.Effort}); 

各研究者だけ各プロジェクトでのロールを持っているかもしれないので、それぞれの努力がBudgetPeriodに研究者によってコミットと仮定しても安全ですその役割によって行われます。

これは

​​に私のクエリを変更する