querying pocketbase relational data
25.07.2023 1 min readSay you have a Posts
collection. Every Post
is related to a User
. How can we fetch relational fields when we get Posts
?
await pb.collection("posts").getFullList({
filter: `user_id="${userId}"`, // get posts by user_id
expand: "user_id",
});
expand
is the option that lets us add the fields related to a user (we assume that the relational column is titled user_id
). The data is returned to us as such:
{
title: "Some title",
content: "Some content",
expand: {
// username, email, created, etc. ALL the fields on a user record
}
}
But maybe we don’t want all the fields. We can limit them by querying only certain fields:
await pb.collection("posts").getFullList({
filter: `user_id="${userId}"`,
expand: "user_id",
fields: "title,content,expand.user_id.username",
});
Built with Astro and Tailwind 🚀