简体   繁体   中英

Achieve a transitive association for a query in SailsJS

My question might be an obvious one, however i've been struggling with this one for a couple of nights. Here's a basic overview of my problem.

I have the following three models:

Model 1

/* api/models/Parent.js */

module.exports = {
  tableName: "table1",
  attributes: {
    name: {
      type: "string",
    },
    children: {
      collection: "child",
      via: "parentId"
    },
  },
};

Model 2

/* api/models/Child.js */

module.exports = {
  tableName: "table2",
  attributes: {
    name: {
      type: "string",
    },
    parentId: {
      model: "parent"
    },
    vaccinations: {
      collection: "vaccination",
      via: "childId"
    },
  },
};

Model 3

/* api/models/Result.js */

module.exports = {
  tableName: "table3",
  attributes: {
    name: {
      type: "string",
    },
    childId: {
      model: "child"
    },
    vaccinationId: {
      model: "vaccination"
    },
  },
};

I wish to be able to query the following GET /vaccination?parentId=1 which will retrieve all vaccinations for children that have parentId=1 . I am not sure what's the best practice to follow here, i would really appreciate any help. I have read the Through Associations but for some reason, i can not get it to work.

Thanks in advance.

Following query might help you here:

let children = await Child.find({
  parentId: 1
})
.populate('parentId')
.populate('vaccinations');

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