- Get Started
- Product
- Resources
- Tools & SDKs
- Framework
- Reference
- Get Started
- Product
- Resources
- Tools & SDKs
- Framework
- Reference
4.2.4. Retrieve Brand linked to Product using Query
What is Query?#
Query is a utility that retrieves data across modules and their links. It’s registered in the Medusa container under the ContainerRegistrationKeys.QUERY
(query
) registration name.
Retrieve Brand of Product API Route#
You'll create an API route that retrieves the brand of a product. You'll use this in a later chapter.
Create the file src/api/admin/products/[id]/brand/route.ts
with the following content:
7} from "@medusajs/framework/utils"8 9export const GET = async (10 req: MedusaRequest,11 res: MedusaResponse12) => {13 const query = req.scope.resolve(14 ContainerRegistrationKeys.QUERY15 )16 17 const { data: [product] } = await query.graph({18 entity: "product",19 fields: ["brand.*"],20 filters: {21 id: req.params.id,22 },23 })24 25 res.json({ brand: product.brand })26}
In this example, you retrieve a product by its ID with its brand, and return the brand in the response.
query.graph Parameters#
The graph
method of Query runs a query to retrieve data. It accepts an object having the following properties:
entity
: The data model's name as specified in the first parameter ofmodel.define
.fields
: An array of properties and relations to retrieve. You can pass:- A property's name, such as
id
. - A relation or linked model's name, such as
brand
. You suffix the name with.*
to retrieve all its properties.
- A property's name, such as
filters
: An object of filters to apply on the retrieved data model's properties.
Test it Out#
To test the API route out, first, retrieve the authentication token of your admin user by sending a POST
request to /auth/user/emailpass
:
Make sure to replace the email and password with your user's credentials.
Then, send a GET
request to /admin/products/:id/brand
:
This returns the product's brand if it has one. For example:
Retrieve Products of a Brand#
An example of retrieving the products of a brand:
In this case, since a brand has multiple products, you specify the plural name of the Product
data model (products
) in fields
.
The retrieved brand
now has a products
field, which is an array of products linked to it:
Summary#
By following the examples of the previous chapters, you:
- Defined a link between the Brand and Product modules's data models, as if you're extending the
Product
model to add a brand. - Created a link between brand and product records.
- Queried the brand linked to a product, and vice versa.
Next Steps#
In the next chapters, you'll learn how to customize the Medusa Admin to show brands.