Sequelize - subquery in where clause

前端 未结 1 1068
伪装坚强ぢ
伪装坚强ぢ 2020-12-25 15:10

I\'m using Sequelize in my Express app. I need to generate a query that has a subquery in the WHERE clause.

SELECT *
  FROM MyTable
 WH         


        
相关标签:
1条回答
  • 2020-12-25 15:50

    I have encountered a similar issue in my project. The way I choose to implement it is a bit different for two reasons:

    1. If at one point in time Sequelize decides to implement sub queries - the syntax is ready.
    2. Use Sequelize protection against SQL injection.

    Here is my code snippet, hope it helps.

    Sequelize v5

    const tempSQL = sequelize.dialect.QueryGenerator.selectQuery('MyOtherTable',{
        attributes: ['fkey'],
        where: {
              field1: 1,
              field2: 2,
              field3: 3
        }})
        .slice(0,-1); // to remove the ';' from the end of the SQL
    
    MyTable.find( {
        where: {
            id: {
                  [Sequelize.Op.notIn]: sequelize.literal(`(${tempSQL})`)
            }
        } 
    } );
    

    Sequelize v6

    const tempSQL = sequelize.dialect.queryGenerator.selectQuery('MyOtherTable',{
        attributes: ['fkey'],
        where: {
              field1: 1,
              field2: 2,
              field3: 3
        }})
        .slice(0,-1); // to remove the ';' from the end of the SQL
    
    MyTable.find( {
        where: {
            id: {
                  [Sequelize.Op.notIn]: sequelize.literal(`(${tempSQL})`)
            }
        } 
    } );
    

    Some people might choose to not use the tempSQL variable and simply build the SQL inside the find structure (maybe using a helper method?)

    I also think this might be the basis for a sub queries extension for sequelize as it uses the same syntax almost.

    0 讨论(0)
提交回复
热议问题