2016-11-26 48 views
0

我有4個型號。 FactoryCarDriverConfig通過其他型號連接

Factory s有Car s。 A Config屬於FactoryCar。 A Driver僅屬於Car,但由於該關聯,我希望它們也屬於Factory

本質上,我想查詢查找特定驅動程序的所有Config。也就是說,所有Car的和Driver驅動的Config,以及Driver通過Car有關的所有Factory

這裏是如何的關係成立:

Factory.hasMany(Config); 
Factory.hasMany(Car); 

Car.belongsToMany(Driver, { through: 'CarDrivers' }); 
Car.hasMany(Config); 
Car.belongsTo(Factory); 

Driver.belongsToMany(Car, { through: 'CarDrivers' }); 

Config.belongsTo(Car); 
Config.belongsTo(Factory); 

我想查詢這樣的:

const configs = await Config.findAll({ 
    where: { relatedUserId: ?? }, 
}); 

回答

0

你必須包括在其中你想「搜索」的模式。
所以你的情況是這樣的:

const configs = await Config.findAll({ 
    where: { relatedUserId: 1 }, //searches in Config 
    include: [{ 
    model : Driver, 
    where : { someId: 1}//searches in Driver 
}, 
{ 
include: Driver, 
through:{ 
where: { CarId: 1} // searches "through" n:m Table 
} 
}, 
include:[ 
all : true // includes ALL models which are Associated to Config 
] 
] 
}); 

這是某些情況下,包括相關的模型,並在他們那裏進行搜索。
您可能必須將其更改爲適用於您的模型,因爲我現在沒有付費注意您是如何關聯模型的。
查看更多信息他們的文檔:
http://sequelize.readthedocs.io/en/latest/docs/querying/#relations-associations