簡體   English   中英

從GraphQL查詢到Sequelize.js SELECT…WHERE COL1 = X AND(COL2 LIKE Y或COL3 LIKE Y)

[英]Query from GraphQL to Sequelize.js SELECT … WHERE COL1 = X AND (COL2 LIKE Y OR COL3 LIKE Y)

我試圖弄清楚如何用Sequelize.js進行查詢,輸出類似

SELECT ... WHERE C1 = X AND (C2 LIKE '%Y%' OR C3 LIKE '%Y%')... to MySQL

const resolvers = {
  Query: {
    findItems(_, args) {
      return Item.findAll({
        limit: 10,
        active: 1,
        offset: args.offset,
        order: [['created_at', 'DESC']],
        $or: [
          {
            column_a: {
              $like: args.y,
            },
          },
          {
            column_b: {
              $like: args.y,
            },
          }]
      });
    }
  }
}

它正在查詢SELECT * FROM item ORDER BY created_at DESC LIMIT... (無位置)

GraphQL的架構

const typeDefinitions = `
        type Item {
                column_a: String,
                column_b: String,
                active: Int,
        }
        type Query {
                findItems(column_a: String, column_b: String, active: Int, offset: Int): [Item]
        }
        type Mutation {
                //..
        }
        schema {
                query: Query
                mutation: Mutation
}`;
export default [typeDefinitions];

Sequelize.js的文檔沒有解釋如何執行此查詢,我也不知道問題是否來自GraphQL查詢。

這是查詢

{
  findItems(column_a: "hello", column_b:"hello", active: 1, offset: 0) {
    column_a
    column_b
    active
    created_at
  }
}

SELECT * FROM item ORDER BY created_at DESC LIMIT... (無位置)

您始終可以傳遞一個可選的where對象來過濾查詢。 請參閱查詢

const resolvers = {
  Query: {
    findItems(_, args) {
      return Item.findAll({
        where: {
          column_a: args.x
        },
        limit: 10,
        active: 1,
        offset: args.offset,
        order: [['created_at', 'DESC']],
        $or: [
          {
            column_a: {
              $like: args.y,
            },
          },
          {
            column_b: {
              $like: args.y,
            },
          }]
      });
    }
  }
}

必須將$ or放在where內並添加一個美元符號。

const resolvers = {
  Query: {
    findItems(_, args) {
      return Item.findAll({
        where: {
        active: 1,
        $or: [
          {
            column_a: {
              $like: args.y,
            },
          },
          {
            column_b: {
              $like: args.y,
            },
          }],
        },
        limit: 10,
        active: 1,
        offset: args.offset,
        order: [['created_at', 'DESC']],
      });
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM