typescriptormsequelize.jssequelize-typescript

Sequelize Dynamic select attributes? works?


facing one issue like - is it really possible to pass dynamic select attributes to FindAll method? Its not working as its not getting recognized.

selectAttributes= "'x_name','y_name','z_name','start_z'"; //prepare this dynamically
groupBy = ['x_name','y_name','z_name','start_z','start_z']       
const results =  await XX.findAll({
        group:groupBy,           
        attributes:['x_name','y_name','z_name','start_z','start_z',
                                    [Sequelize.fn(Constants.SEQUELIZE_SUM_FUNCTION, 
                                      Sequelize.col(obj.metrics)),obj.metrics]],

        where:result.where , //I have this built dynamically which works great
        order: result.order,//I have this built dynamically which works great

    });

//the above code works and gets all columns in select. but I wanted to pass the columns dynamically along with group and where and order by; I was success with where/orderby/group by but not select attributes. I was making a string and passing it as select attribute but its not recognizing it and returns only SUM column in above code.

How could I generalize the SELECT attributes for FindALL?


Solution

  • possibly this would help others who are looking to build dynamic select attributes.

        selectAttributes= build your array here dynamically //prepare this dynamically
    groupBy = ['x_name','y_name','z_name','start_z','start_z']       
    const results =  await XX.findAll({
            group:groupBy,           
            attributes:[...selectAttributes,                                  [Sequelize.fn(Constants.SEQUELIZE_SUM_FUNCTION,                                       Sequelize.col(obj.tasks)),obj.tasks]],
            where:result.where , //I have this built dynamically which works great
            order: result.order,//I have this built dynamically which works great
        });