0

Doing this query:

select * from menuitems

return new Promise((resolve, reject) => {
 db.transaction((tx) => {
  tx.executeSql(
    "select * from menuitems",
    [`%${query}$%`],
    (_, { rows }) => {
      useDevLogData(rows._array, "filterByQueryAndCategories rows._array");
    }
  );
}, reject);
});

I have this set of result:

[
  {
    "id": 1,
    "uuid": "1.0",
    "title": "Spinach Artichoke Dip",
    "price": "10",
    "category": "Appetizers"
  },
  {
    "id": 2,
    "uuid": "2.0",
    "title": "Hummus",
    "price": "10",
    "category": "Appetizers"
  },
  ...
]

But when i do it like this i have no result: returning empty []

 return new Promise((resolve, reject) => {
    db.transaction((tx) => {
      tx.executeSql(
        "select * from menuitems WHERE title LIKE ?",
        [`%${query}$%`],
        (_, { rows }) => {
          useDevLogData(rows._array, "filterByQueryAndCategories rows._array");
        }
      );
    }, reject);
  });

Also I would need to combine this search text, e.g. %Spinach% query to filter category on an array of categories, e.g. ["Appetizers", "Salads"], How do I query to filter the category column based on array of string? and also based on that, I need to query the field title? I need to do something like:

"select * from menuitems where title LIKE %Spinach% AND category LIKE ["Appetizers", "Salads"]"

2 Answers 2

1

@gpbaculio You have to add parenthesis surrounding column in your answer to handle search to be effective on one or more category column.

tx.executeSql("select * from menuitems where title like ? AND (category = ? OR category = ? OR category = ?)",
    [`%${query}%`, ...activeCategories], (_, { rows }) => {
      resolve(rows._array);
    });

To dynamically handle category you can use map like below

tx.executeSql(
      `select * from menuitems where title LIKE '%${query}%' AND (${activeCategories.map((cat) => 
        `category='${cat}'`).join(' OR ')})`,[], (_, { rows }) => {
          resolve(rows._array);
        });

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

0

Sorry have typo, resolved it like this, I have 3 MAX category:

activeCategories = [
  "Appetizers"
]

 return new Promise((resolve, reject) => {
    db.transaction((tx) => {
      tx.executeSql(
        "select * from menuitems WHERE title LIKE ? AND category = ? OR category = ? OR category = ?",
        [`%${query}%`, ...activeCategories],
        (_, { rows }) => {
          useDevLogData(rows._array, "filterByQueryAndCategories rows._array");
        }
      );
    }, reject);
  });

Might help someone like me new to SQL, this seem works for me now

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.