4.2.1. Define Link Between a Brand and a Product

Example ChapterThis chapter covers how to define a link between the Brand and Product data models as a step of the "Extend Models" chapter .

Links are defined in a TypeScript or JavaScript file under the src/links directory. The file defines and exports the link using the defineLink function imported from @medusajs/framework/utils.

So, create the file src/links/product-brand.ts with the following content:

src/links/product-brand.ts
1import BrandModule from "../modules/brand"2import ProductModule from "@medusajs/medusa/product"3import { defineLink } from "@medusajs/framework/utils"4
5export default defineLink(6  {7    linkable: ProductModule.linkable.product,8    isList: true,9  },10  BrandModule.linkable.brand11)

The defineLink function accepts two parameters, each specifying the link configurations of each data model.

Modules have a special linkable property that holds the data models' link configurations.

defineLink accepts for each parameter either:

  • The data model's link configuration;
  • Or an object that has two properties:
    • linkable: the link configuration of the data model.
    • isList: Whether many records of the data model can be linked to the other model.

So, in the above code snippet, you define a link between the Product and Brand data models. Since isList is enabled on the product's side, a brand can be associated with multiple products.


To reflect your link in the database, run the db:sync-links command:

Terminal
npx medusa db:sync-links

This creates a table for the link in the database. The table stores the IDs of linked brand and product records.

TipYou can also use the db:migrate command, which both runs the migrations and syncs the links.

In the next chapter, you'll learn how to associate brand and product records by creating a link between them.

Was this chapter helpful?
Edit this page