2016-11-26 106 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