简体   繁体   中英

How to query objects with property contains a value in loopback

I have a model event which referenceMany user .

"relations": {
  "attendees": {
    "type": "referencesMany",
    "model": "user",
    "foreignKey": "attendeeIds",
    "options": {
      "validate": true,
      "forceId": false,
      "persistent": true
   }
}

How can I query event which attendees property contain a given value? attendees is an array containing userId.

For example:

Event.find({
    where: {
      attendees: {
        contains: givenUserId
      }
    }
  }
)

This feature is called 'Filter on level 2 properties' as referenced here and is being implemented for Memory and MongoDB connectors. It still has some issues. For SQL connectors, this isn't supported yet and - as mentioned also inside this open discussion link - it requires some time which cannot be afforded now.

Possible work around here with regexp that would apply to the underlying JSON string and executing SQL directly via datasource.connector.execute()

Simple implementaion could be:

AnyModel.getApp((err, app) => {
  if (err) {
    console.log(err);
    next(err);
  }

  // Using MySQL
  const MySQL = app.dataSources.MySQL;

  MySQL.connector.execute(`select * from Table where column like '%${string}%'`,
    [], {}, (err, data) => {
      if (err) {
        console.log(err);
        next(err);
      }

      console.log(data);
      next();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM