How to Query a Model based on its Relation in Strapi

Viewed 10140

Hope you are all having a nice day! :) I have tried to google my question but never can get a working example.

I have a model for Projects. Projects has a 1:n relationship with the model Members. If I use:

strapi.query('project').find({id: 1});

I get:

{ id: 1, name: 'Project 1', members: [...]}

So basically I am able to find a Project by its ID and I get a list of its Members.

BUT how would I go about getting a list of all members that belong to Project with ID = 1?

strapi.query('member').find(...);
strapi.query('member').search(...);

The closest I got was using:

strapi.query('member').search({_q: 'Project Name'});

This is however not close enough. It is more of a work around. I would really like to be able to do this in a clean way by using the IDs of the Project. Can anyone help or point me in the right direction? Any examples are greatly appreciated! Thank you! :)

2 Answers

The best way to do this is:

strapi.query('member').find({name:'','project.id':id});

Above is AND find

strapi.query('member').find({name:''},['project.id',id]);

Above is OR find

You can add a custom controller function in project/controller/project.js

getMembers: async ctx => {
  const {id} = ctx.params; 
  const project = await strapi.services.project.findOne({id});
  
  return project ? project.members : [];
}

Make sure that you expose the route. Add the following in project/config/routes.json

{
  "method": "GET",
  "path": "/projects/get-members/:id",
  "handler": "project.getMembers",
  "config": {
    "policies": []
  }
},

You can also change the "path" property to whatever suits your needs.

Related