In Payload CMS, querying data dynamically is a powerful way to build flexible APIs. By using custom query parameters, you can implement advanced filtering to fetch specific records based on your application’s needs.
Define the Collection
const Posts = {
slug: 'posts',
fields: [
{ name: 'title', type: 'text', required: true },
{ name: 'content', type: 'textarea', required: true },
{
name: 'category',
type: 'relationship',
relationTo: 'categories',
required: true,
},
{
name: 'author',
type: 'relationship',
relationTo: 'users',
required: true,
},
],
};
export default Posts;
I) Use Query Parameters
To filter posts by category or author, use query parameters in the API request:
GET /api/posts?where[category][equals]=123&where[author][equals]=456
II) Dynamic Filtering in Code
const fetchFilteredPosts = async (categoryId, authorId) => {
const response = await fetch(`/api/posts?where[category][equals]=${categoryId}&where[author][equals]=${authorId}`);
const data = await response.json();
return data.docs;
};
fetchFilteredPosts('123', '456').then(posts => {
console.log('Filtered Posts:', posts);
});
Benefits of Dynamic Filtering
- Fetch only the data you need, improving API efficiency.
- Combine multiple filters for precise control.