问题
I need to select all SPR_TYPE_UM and SPR_TYPE_ASSETS for editing window, but one SPR_TYPE_ASSETS.
router.get('/edit/:assetId', function (req, res) {
models.SPR_ASSET.findAll({
include: [models.SPR_TYPE_UM, models.SPR_TYPE_ASSETS],
// need to include all um and types here
where: { ID_ASSET: req.params.assetId}
}).then(function(data) {
console.log(data);
res.render('assets/edit', {
title: 'Assets specification',
data: data
});
});
});
Associations
SPR_ASSET.belongsTo(models.SPR_TYPE_UM, {foreignKey: 'ID_TYPE_UM', onUpdate: "NO ACTION"});
SPR_ASSET.belongsTo(models.SPR_TYPE_ASSETS, {foreignKey: 'ID_TYPE_ASSETS', onUpdate: "NO ACTION"});
SPR_TYPE_UM.hasMany(models.SPR_ASSET, {foreignKey: 'ID_TYPE_UM'});
SPR_TYPE_ASSETS.hasMany(models.SPR_ASSET, {foreignKey: 'ID_TYPE_ASSETS'});
Maybe I have wrong associations, or should I do this with raw query?
This query give only one record from SPR_ASSET, SPR_TYPE_UM and SPR_TYPE_ASSETS .
I need one record from SPR_ASSET and all records from SPR_TYPE_UM and SPR_TYPE_ASSETS.
回答1:
For me that was solution, maybe there was better ways to do it
router.get('/edit/:assetId', function (req, res) {
models.SPR_ASSET.findAll({
where: { ID_ASSET: req.params.assetId}
}).then(function(SPR_ASSET_DATA) {
models.SPR_TYPE_UM.findAll().then(function(SPR_TYPE_UM_DATA){
models.SPR_TYPE_ASSETS.findAll().then(function(SPR_TYPE_ASSETS_DATA){
var data ={
SPR_ASSET: SPR_ASSET_DATA,
SPR_TYPE_UM: SPR_TYPE_UM_DATA,
SPR_TYPE_ASSET: SPR_TYPE_ASSETS_DATA
}
console.log(data);
res.render('assets/edit', {
title: 'Справочник спецификаций',
data: data
});
})
})
});
});
};
来源:https://stackoverflow.com/questions/33970624/querying-multiple-models-with-sequelize-js-orm