How to pass data between Includes in the same query of sequelize?

0

I have a problem with sequelize, I need to consult several tables in the same query, these are nested with Include: [] so fine, but I need to pass the result of a nested table (coins) to another table of another include (prices), since with respect to that value of the table coins a WHERE must be made in the table prices.

Example code:

db.tiendas.findAll({
  where : {id_tienda: '4'},
  attributes: ['id_tienda'],
  include : [
    {
      model : db.cuentas,       
      as : "cuentas",
      attributes: ['id_cuenta','numero'],
      required: false,
      include : [
        {
          model : db.monedas, // MONEDAS
          as : "monedas",
          attributes: ['id_moneda'], // este valor es el que se tiene que pasar a la tabla precios ubicada mas abajo
          required: false                      
        }
      ]      
    },
    {
      model : db.programas, 
      as : "programas",
      attributes: ['titulo'],
      required: false,     
      include : [          
        {
          model : db.precios, //PRECIOS 
          as : "precio"
          where: {id_moneda: /*aqui necesito el id_moneda*/ }]},
          attributes: ['valor'],
          through: { attributes: [] },
          required: false         
        }
      ]
    }]}).then((datos)=>{console.log(datos)})

Thank you for the time given.

    
asked by David Fernando Zapata 23.09.2018 в 21:51
source

1 answer

0

What I would do, is to put a subquery in the where, something like this:

 db.tiendas.findAll({
  where : {id_tienda: '4'},
  attributes: ['id_tienda'],
  include : [
    {
      model : db.cuentas,       
      as : "cuentas",
      attributes: ['id_cuenta','numero'],
      required: false,
      include : [
        {
          model : db.monedas, // MONEDAS
          as : "monedas",
          attributes: ['id_moneda'], // este valor es el que se tiene que pasar a la tabla precios ubicada mas abajo
          required: false                      
        }
      ]      
    },
    {
      model : db.programas, 
      as : "programas",
      attributes: ['titulo'],
      required: false,     
      include : [          
        {
          model : db.precios, //PRECIOS 
          as : "precio"
          where: {id_moneda: db.sequelize.literal('(select id_moneda from cuentas where id_tienda = 4)') },
          attributes: ['valor'],
          through: { attributes: [] },
          required: false         
        }
      ]
    }
  ]}).then((datos)=>{console.log(datos)})

I would need to see the structure of your tables to know the subquery well, but I think this could help you.

Greetings

    
answered by 24.09.2018 в 16:45