3.4.2. Link
In this chapter, you’ll learn what Link is and how to use it to manage links.
What is Link?#
Link is a class with utility methods to manage links between data models. It’s registered in the Medusa container under the link registration name.
For example:
You can use its methods to manage links, such as create or delete links.
Create Link#
To create a link between records of two data models, use the create method of Link.
For example:
The create method accepts as a parameter an object. The object’s keys are the names of the linked modules.
The value of each module’s property is an object, whose keys are of the format {data_model_snake_name}_id, and values are the IDs of the linked record.
So, in the example above, you link a record of the MyCustom data model in a hello module to a Product record in the Product Module.
Enforced Integrity Constraints on Link Creation#
Medusa enforces integrity constraints on links based on the link's relation type. So, an error is thrown in the following scenarios:
- If the link is one-to-one and one of the linked records already has a link to another record of the same data model. For example:
1// no error2await link.create({3 [Modules.PRODUCT]: {4 product_id: "prod_123",5 },6 "helloModuleService": {7 my_custom_id: "mc_123",8 },9})10 11// throws an error because `prod_123` already has a link to `mc_123`12await link.create({13 [Modules.PRODUCT]: {14 product_id: "prod_123",15 },16 "helloModuleService": {17 my_custom_id: "mc_456",18 },19})
- If the link is one-to-many and the "one" side already has a link to another record of the same data model. For example, if a product can have many
MyCustomrecords, but aMyCustomrecord can only have one product:
1// no error2await link.create({3 [Modules.PRODUCT]: {4 product_id: "prod_123",5 },6 "helloModuleService": {7 my_custom_id: "mc_123",8 },9})10 11// also no error12await link.create({13 [Modules.PRODUCT]: {14 product_id: "prod_123",15 },16 "helloModuleService": {17 my_custom_id: "mc_456",18 },19})20 21// throws an error because `mc_123` already has a link to `prod_123`22await link.create({23 [Modules.PRODUCT]: {24 product_id: "prod_456",25 },26 "helloModuleService": {27 my_custom_id: "mc_123",28 },29})
There are no integrity constraints in a many-to-many link, so you can create multiple links between the same records.
Dismiss Link#
To remove a link between records of two data models, use the dismiss method of Link.
For example:
The dismiss method accepts the same parameter type as the create method.
Cascade Delete Linked Records#
If a record is deleted, use the delete method of Link to delete all linked records.
For example:
This deletes all records linked to the deleted product.
Restore Linked Records#
If a record that was previously soft-deleted is now restored, use the restore method of Link to restore all linked records.
For example: