Querying multiple models with Sequelize.js ORM

痞子三分冷 提交于 2019-12-10 20:02:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!