1 export const metadata = {
2 title: `${pageNumber} Manage Relationships`,
3 }
4
5 # {metadata.title}
6
7 In this chapter, you'll learn how to manage relationships between data models when creating, updating, or retrieving records using the module's main service.
8
9 <Note>
10
11 This chapter applies to data model relationships within the same module. To manage linked data models across modules, check out [Links](../../module-links/page.mdx) and [Query](../../query/page.mdx).
12
13 </Note>
14
15 ## Manage One-to-One Relationship
16
17 ### BelongsTo Side of One-to-One
18
19 When you create a record of a data model that belongs to another through a one-to-one relation, pass the ID of the other data model's record in the `{relation}_id` property, where `{relation}` is the name of the relation property.
20
21 For example, assuming you have the [User and Email data models from the previous chapter](../relationships/page.mdx#one-to-one-relationship), set an email's user ID as follows:
22
23 export const belongsHighlights = [
24 ["4", "user_id", "The ID of the user the email belongs to."],
25 ["11", "user_id", "The ID of the user the email belongs to."]
26 ]
27
28 ```ts highlights={belongsHighlights}
29 // when creating an email
30 const email = await helloModuleService.createEmails({
31 // other properties...
32 user_id: "123",
33 })
34
35 // when updating an email
36 const email = await helloModuleService.updateEmails({
37 id: "321",
38 // other properties...
39 user_id: "123",
40 })
41 ```
42
43 In the example above, you pass the `user_id` property when creating or updating an email to specify the user it belongs to.
44
45 ### HasOne Side
46
47 When you create a record of a data model that has one of another, pass the ID of the other data model's record in the relation property.
48
49 For example, assuming you have the [User and Email data models from the previous chapter](../relationships/page.mdx#one-to-one-relationship), set a user's email ID as follows:
50
51 export const hasOneHighlights = [
52 ["4", "email", "The ID of the email that the user has."],
53 ["11", "email", "The ID of the email that the user has."]
54 ]
55
56 ```ts highlights={hasOneHighlights}
57 // when creating a user
58 const user = await helloModuleService.createUsers({
59 // other properties...
60 email: "123",
61 })
62
63 // when updating a user
64 const user = await helloModuleService.updateUsers({
65 id: "321",
66 // other properties...
67 email: "123",
68 })
69 ```
70
71 In the example above, you pass the `email` property when creating or updating a user to specify the email it has.
72
73 ---
74
75 ## Manage One-to-Many Relationship
76
77 In a one-to-many relationship, you can only manage the associations from the `belongsTo` side.
78
79 When you create a record of the data model on the `belongsTo` side, pass the ID of the other data model's record in the `{relation}_id` property, where `{relation}` is the name of the relation property.
80
81 For example, assuming you have the [Product and Store data models from the previous chapter](../relationships/page.mdx#one-to-many-relationship), set a product's store ID as follows:
82
83 export const manyBelongsHighlights = [
84 ["4", "store_id", "The ID of the store the product belongs to."],
85 ["11", "store_id", "The ID of the store the product belongs to."]
86 ]
87
88 ```ts highlights={manyBelongsHighlights}
89 // when creating a product
90 const product = await helloModuleService.createProducts({
91 // other properties...
92 store_id: "123",
93 })
94
95 // when updating a product
96 const product = await helloModuleService.updateProducts({
97 id: "321",
98 // other properties...
99 store_id: "123",
100 })
101 ```
102
103 In the example above, you pass the `store_id` property when creating or updating a product to specify the store it belongs to.
104
105 ---
106
107 ## Manage Many-to-Many Relationship
108
109 <Note>
110
111 If your many-to-many relation is represented with a [pivotEntity](../relationships/page.mdx#many-to-many-with-custom-columns), refer to [this section](#manage-many-to-many-relationship-with-pivotentity) instead.
112
113 </Note>
114
115 ### Create Associations
116
117 When you create a record of a data model that has a many-to-many relationship to another data model, pass an array of IDs of the other data model's records in the relation property.
118
119 For example, assuming you have the [Order and Product data models from the previous chapter](../relationships/page.mdx#many-to-many-relationship), set the association between products and orders as follows:
120
121 export const manyHighlights = [
122 ["4", "orders", "The IDs of the orders associated with the product."],
123 ["11", "products", "The IDs of the products associated with the order."]
124 ]
125
126 ```ts highlights={manyHighlights}
127 // when creating a product
128 const product = await helloModuleService.createProducts({
129 // other properties...
130 orders: ["123", "321"],
131 })
132
133 // when creating an order
134 const order = await helloModuleService.createOrders({
135 id: "321",
136 // other properties...
137 products: ["123", "321"],
138 })
139 ```
140
141 In the example above, you pass the `orders` property when you create a product, and you pass the `products` property when you create an order.
142
143 ### Update Associations
144
145 When you use the `update` methods generated by the service factory, you also pass an array of IDs as the relation property's value to add new associated records.
146
147 However, this removes any existing associations to records whose IDs aren't included in the array.
148
149 For example, assuming you have the [Order and Product data models from the previous chapter](../relationships/page.mdx#many-to-many-relationship), you update the product's related orders as so:
150
151 ```ts
152 const product = await helloModuleService.updateProducts({
153 id: "123",
154 // other properties...
155 orders: ["321"],
156 })
157 ```
158
159 If the product was associated with an order, and you don't include that order's ID in the `orders` array, the association between the product and order is removed.
160
161 So, to add a new association without removing existing ones, retrieve the product first to pass its associated orders when updating the product:
162
163 export const updateAssociationHighlights = [
164 ["1", "retrieveProduct", "Retrieve the product with its orders."],
165 ["12", "", "Pass the IDs of the orders previously associated with the product."],
166 ["13", "", "Associate the product with a new order."]
167 ]
168
169 ```ts highlights={updateAssociationHighlights}
170 const product = await helloModuleService.retrieveProduct(
171 "123",
172 {
173 relations: ["orders"],
174 }
175 )
176
177 const updatedProduct = await helloModuleService.updateProducts({
178 id: product.id,
179 // other properties...
180 orders: [
181 ...product.orders.map((order) => order.id),
182 "321",
183 ],
184 })
185 ```
186
187 This keeps existing associations between the product and orders, and adds a new one.
188
189 ---
190
191 ## Manage Many-to-Many Relationship with pivotEntity
192
193 <Note>
194
195 If your many-to-many relation is represented without a [pivotEntity](../relationships/page.mdx#many-to-many-with-custom-columns), refer to [this section](#manage-many-to-many-relationship) instead.
196
197 </Note>
198
199 If you have a many-to-many relation with a `pivotEntity` specified, make sure to pass the data model representing the pivot table to [MedusaService](../../modules/service-factory/page.mdx) that your module's service extends.
200
201 For example, assuming you have the [Order, Product, and OrderProduct models from the previous chapter](../relationships/page.mdx#many-to-many-with-custom-columns), add `OrderProduct` to `MedusaService`'s object parameter:
202
203 ```ts highlights={["4"]}
204 class BlogModuleService extends MedusaService({
205 Order,
206 Product,
207 OrderProduct,
208 }) {}
209 ```
210
211 This will generate Create, Read, Update and Delete (CRUD) methods for the `OrderProduct` data model, which you can use to create relations between orders and products and manage the extra columns in the pivot table.
212
213 For example:
214
215 ```ts
216 // create order-product association
217 const orderProduct = await blogModuleService.createOrderProducts({
218 order_id: "123",
219 product_id: "123",
220 metadata: {
221 test: true,
222 },
223 })
224
225 // update order-product association
226 const orderProduct = await blogModuleService.updateOrderProducts({
227 id: "123",
228 metadata: {
229 test: false,
230 },
231 })
232
233 // delete order-product association
234 await blogModuleService.deleteOrderProducts("123")
235 ```
236
237 Since the `OrderProduct` data model belongs to the `Order` and `Product` data models, you can set its order and product as explained in the [one-to-many relationship section](#manage-one-to-many-relationship) using `order_id` and `product_id`.
238
239 Refer to the [service factory reference](!resources!/service-factory-reference) for a full list of generated methods and their usages.
240
241 ---
242
243 ## Retrieve Records of Relation
244
245 The `list`, `listAndCount`, and `retrieve` methods of a module's main service accept as a second parameter an object of options.
246
247 To retrieve the records associated with a data model's records through a relationship, pass in the second parameter object a `relations` property whose value is an array of relationship names.
248
249 For example, assuming you have the [Order and Product data models from the previous chapter](../relationships/page.mdx#many-to-many-relationship), you retrieve a product's orders as follows:
250
251 export const retrieveHighlights = [
252 ["4", `"orders"`, "Retrieve the records associated with the product\nthrough the `orders` relationship."]
253 ]
254
255 ```ts highlights={retrieveHighlights}
256 const product = await blogModuleService.retrieveProducts(
257 "123",
258 {
259 relations: ["orders"],
260 }
261 )
262 ```
263
264 In the example above, the retrieved product has an `orders` property, whose value is an array of orders associated with the product.