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! :)
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! :)
Share Improve this question asked Jul 1, 2020 at 15:59 Philipp PanikPhilipp Panik 3432 gold badges5 silver badges17 bronze badges3 Answers
Reset to default 12The 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.
In Strapi v4, using entityService:
strapi.entityService.findMany('api::member.member', {
filters: {
project: {
id: 1
}
}
});
If you want to add details of the project with each record:
strapi.entityService.findMany('api::member.member', {
filters: {
project: {
id: 1
}
},
populate: {
project: true
}
});