|
1
|
export const metadata = { |
|
2
|
title: `${pageNumber} Data Model Relationships`, |
|
3
|
} |
|
4
|
|
|
5
|
# {metadata.title} |
|
6
|
|
|
7
|
In this chapter, you’ll learn how to define relationships between data models in your module. |
|
8
|
|
|
9
|
## What is a Relationship Property? |
|
10
|
|
|
11
|
A relationship property defines an association in the database between two models. It's created using the Data Model Language (DML) methods, such as `hasOne` or `belongsTo`. |
|
12
|
|
|
13
|
When you generate a migration for these data models, the migrations include foreign key columns or pivot tables, based on the relationship's type. |
|
14
|
|
|
15
|
<Note title="Use data model relationships when" type="success"> |
|
16
|
|
|
17
|
You want to create a relation between data models in the same module. |
|
18
|
|
|
19
|
</Note> |
|
20
|
|
|
21
|
<Note title="Don't use data model relationships if" type="error"> |
|
22
|
|
|
23
|
You want to create a relationship between data models in different modules. Use module links instead. |
|
24
|
|
|
25
|
</Note> |
|
26
|
|
|
27
|
--- |
|
28
|
|
|
29
|
## One-to-One Relationship |
|
30
|
|
|
31
|
A one-to-one relationship indicates that one record of a data model belongs to or is associated with another. |
|
32
|
|
|
33
|
To define a one-to-one relationship, create relationship properties in the data models using the following methods: |
|
34
|
|
|
35
|
1. `hasOne`: indicates that the model has one record of the specified model. |
|
36
|
2. `belongsTo`: indicates that the model belongs to one record of the specified model. |
|
37
|
|
|
38
|
For example: |
|
39
|
|
|
40
|
export const oneToOneHighlights = [ |
|
41
|
["5", "hasOne", "A user has one email."], |
|
42
|
["6", `"user"`, "The relationship's name in the `Email` data model."], |
|
43
|
["12", "belongsTo", "An email belongs to a user."], |
|
44
|
["13", `"email"`, "The relationship's name in the `User` data model."] |
|
45
|
] |
|
46
|
|
|
47
|
```ts highlights={oneToOneHighlights} |
|
48
|
import { model } from "@medusajs/framework/utils" |
|
49
|
|
|
50
|
const User = model.define("user", { |
|
51
|
id: model.id().primaryKey(), |
|
52
|
email: model.hasOne(() => Email, { |
|
53
|
mappedBy: "user", |
|
54
|
}), |
|
55
|
}) |
|
56
|
|
|
57
|
const Email = model.define("email", { |
|
58
|
id: model.id().primaryKey(), |
|
59
|
user: model.belongsTo(() => User, { |
|
60
|
mappedBy: "email", |
|
61
|
}), |
|
62
|
}) |
|
63
|
``` |
|
64
|
|
|
65
|
In the example above, a user has one email, and an email belongs to one user. |
|
66
|
|
|
67
|
The `hasOne` and `belongsTo` methods accept a function as the first parameter. The function returns the associated data model. |
|
68
|
|
|
69
|
Both methods also accept a second parameter object with the property `mappedBy`. Its value is the name of the relationship property in the other data model. |
|
70
|
|
|
71
|
### Optional Relationship |
|
72
|
|
|
73
|
To make the relationship optional on the `hasOne` or `belongsTo` side, use the `nullable` method on either property as explained in [this chapter](../properties/page.mdx#make-property-optional). |
|
74
|
|
|
75
|
### One-to-One Relationship in the Database |
|
76
|
|
|
77
|
When you generate the migrations of data models that have a one-to-one relationship, the migration adds to the table of the data model that has the `belongsTo` property: |
|
78
|
|
|
79
|
1. A column of the format `{relation_name}_id` to store the ID of the record of the related data model. For example, the `email` table will have a `user_id` column. |
|
80
|
2. A foreign key on the `{relation_name}_id` column to the table of the related data model. |
|
81
|
|
|
82
|
 |
|
83
|
|
|
84
|
### One-sided One-to-One Relationship |
|
85
|
|
|
86
|
In some use cases, you may want to define a one-to-one relationship only on one side. This means that the other data model does not have a relationship property pointing to the first one. |
|
87
|
|
|
88
|
You can do this either from the `hasOne` or the `belongsTo` side. |
|
89
|
|
|
90
|
#### hasOne Side |
|
91
|
|
|
92
|
By default, the foreign key column is added to the table of the data model that has the `belongsTo` property. For example, if the `Email` data model belongs to the `User` data model, then the foreign key column is added to the `email` table. |
|
93
|
|
|
94
|
If you want to define a one-to-one relationship only on the `User` data model's side (`hasOne` side), you can do so by passing the following properties to the second parameter of the `hasOne` method: |
|
95
|
|
|
96
|
- `foreignKey`: A boolean indicating whether the foreign key column should be added to the table of the data model. |
|
97
|
- `mappedBy`: Set to `undefined`, since the relationship is only defined on one side. |
|
98
|
|
|
99
|
For example: |
|
100
|
|
|
101
|
export const oneToOneForeignKeyHighlights = [ |
|
102
|
["5", "hasOne", "A user has one email."], |
|
103
|
["6", "foreignKey", "Add the foreign key column to the `user` table."], |
|
104
|
["7", "mappedBy", "Set to `undefined` since the relationship is only defined on the `User` data model."], |
|
105
|
] |
|
106
|
|
|
107
|
```ts highlights={oneToOneForeignKeyHighlights} |
|
108
|
import { model } from "@medusajs/framework/utils" |
|
109
|
|
|
110
|
const User = model.define("user", { |
|
111
|
id: model.id().primaryKey(), |
|
112
|
email: model.hasOne(() => Email, { |
|
113
|
foreignKey: true, |
|
114
|
mappedBy: undefined, |
|
115
|
}), |
|
116
|
}) |
|
117
|
|
|
118
|
const Email = model.define("email", { |
|
119
|
id: model.id().primaryKey(), |
|
120
|
}) |
|
121
|
``` |
|
122
|
|
|
123
|
In the example above, you add a one-to-one relationship from the `User` data model to the `Email` data model. |
|
124
|
|
|
125
|
The foreign key column is added to the `user` table, and the `Email` data model does not have a relationship property pointing to the `User` data model. |
|
126
|
|
|
127
|
|
|
128
|
#### belongsTo Side |
|
129
|
|
|
130
|
To define the one-to-one relationship on the `belongsTo` side, pass `undefined` to the `mappedBy` property in the `belongsTo` method's second parameter. |
|
131
|
|
|
132
|
For example: |
|
133
|
|
|
134
|
export const oneToOneUndefinedHighlights = [ |
|
135
|
["10", "undefined", "Pass `undefined` since the relationship is only defined on the `Email` data model."] |
|
136
|
] |
|
137
|
|
|
138
|
```ts highlights={oneToOneUndefinedHighlights} |
|
139
|
import { model } from "@medusajs/framework/utils" |
|
140
|
|
|
141
|
const User = model.define("user", { |
|
142
|
id: model.id().primaryKey(), |
|
143
|
}) |
|
144
|
|
|
145
|
const Email = model.define("email", { |
|
146
|
id: model.id().primaryKey(), |
|
147
|
user: model.belongsTo(() => User, { |
|
148
|
mappedBy: undefined, |
|
149
|
}), |
|
150
|
}) |
|
151
|
``` |
|
152
|
|
|
153
|
In the example above, you add a one-to-one relationship from the `Email` data model to the `User` data model. |
|
154
|
|
|
155
|
The `User` data model does not have a relationship property pointing to the `Email` data model. |
|
156
|
|
|
157
|
--- |
|
158
|
|
|
159
|
## One-to-Many Relationship |
|
160
|
|
|
161
|
A one-to-many relationship indicates that one record of a data model has many records of another data model. |
|
162
|
|
|
163
|
To define a one-to-many relationship, create relationship properties in the data models using the following methods: |
|
164
|
|
|
165
|
1. `hasMany`: indicates that the model has more than one record of the specified model. |
|
166
|
2. `belongsTo`: indicates that the model belongs to one record of the specified model. |
|
167
|
|
|
168
|
For example: |
|
169
|
|
|
170
|
export const oneToManyHighlights = [ |
|
171
|
["5", "hasMany", "A store has many products."], |
|
172
|
["6", `"store"`, "The relationship's name in the `Product` data model."], |
|
173
|
["12", "belongsTo", "A product has one store."], |
|
174
|
["13", `"products"`, "The relationship's name in the `Store` data model."] |
|
175
|
] |
|
176
|
|
|
177
|
```ts highlights={oneToManyHighlights} |
|
178
|
import { model } from "@medusajs/framework/utils" |
|
179
|
|
|
180
|
const Store = model.define("store", { |
|
181
|
id: model.id().primaryKey(), |
|
182
|
products: model.hasMany(() => Product, { |
|
183
|
mappedBy: "store", |
|
184
|
}), |
|
185
|
}) |
|
186
|
|
|
187
|
const Product = model.define("product", { |
|
188
|
id: model.id().primaryKey(), |
|
189
|
store: model.belongsTo(() => Store, { |
|
190
|
mappedBy: "products", |
|
191
|
}), |
|
192
|
}) |
|
193
|
``` |
|
194
|
|
|
195
|
In this example, a store has many products, but a product belongs to one store. |
|
196
|
|
|
197
|
### Optional Relationship |
|
198
|
|
|
199
|
To make the relationship optional on the `belongsTo` side, use the `nullable` method on the property as explained in [this chapter](../properties/page.mdx#make-property-optional). |
|
200
|
|
|
201
|
### One-to-Many Relationship in the Database |
|
202
|
|
|
203
|
When you generate the migrations of data models that have a one-to-many relationship, the migration adds to the table of the data model that has the `belongsTo` property: |
|
204
|
|
|
205
|
1. A column of the format `{relation_name}_id` to store the ID of the record of the related data model. For example, the `product` table will have a `store_id` column. |
|
206
|
2. A foreign key on the `{relation_name}_id` column to the table of the related data model. |
|
207
|
|
|
208
|
 |
|
209
|
|
|
210
|
--- |
|
211
|
|
|
212
|
## Many-to-Many Relationship |
|
213
|
|
|
214
|
A many-to-many relationship indicates that many records of a data model can be associated with many records of another data model. |
|
215
|
|
|
216
|
To define a many-to-many relationship, create relationship properties in the data models using the `manyToMany` method. |
|
217
|
|
|
218
|
For example: |
|
219
|
|
|
220
|
export const manyToManyHighlights = [ |
|
221
|
["5", "manyToMany", "An order is associated with many products."], |
|
222
|
["15", "manyToMany", "A product is associated with many orders."] |
|
223
|
] |
|
224
|
|
|
225
|
```ts highlights={manyToManyHighlights} |
|
226
|
import { model } from "@medusajs/framework/utils" |
|
227
|
|
|
228
|
const Order = model.define("order", { |
|
229
|
id: model.id().primaryKey(), |
|
230
|
products: model.manyToMany(() => Product, { |
|
231
|
mappedBy: "orders", |
|
232
|
pivotTable: "order_product", |
|
233
|
joinColumn: "order_id", |
|
234
|
inverseJoinColumn: "product_id", |
|
235
|
}), |
|
236
|
}) |
|
237
|
|
|
238
|
const Product = model.define("product", { |
|
239
|
id: model.id().primaryKey(), |
|
240
|
orders: model.manyToMany(() => Order, { |
|
241
|
mappedBy: "products", |
|
242
|
}), |
|
243
|
}) |
|
244
|
``` |
|
245
|
|
|
246
|
The `manyToMany` method accepts two parameters: |
|
247
|
|
|
248
|
1. A function that returns the associated data model. |
|
249
|
2. An object of optional configuration. Only one of the data models in the relation can define the `pivotTable`, `joinColumn`, and `inverseJoinColumn` configurations, and it's considered the owner data model. The object can accept the following properties: |
|
250
|
- `mappedBy`: The name of the relationship property in the other data model. If not set, the property's name is inferred from the associated data model's name. |
|
251
|
- `pivotTable`: The name of the pivot table created in the database for the many-to-many relation. If not set, the pivot table is inferred by combining the names of the data models' tables in alphabetical order, separating them by `_`, and pluralizing the last name. For example, `order_products`. |
|
252
|
- `joinColumn`: The name of the column in the pivot table that points to the owner model's primary key. |
|
253
|
- `inverseJoinColumn`: The name of the column in the pivot table that points to the owned model's primary key. |
|
254
|
|
|
255
|
<Note> |
|
256
|
|
|
257
|
The `pivotTable`, `joinColumn`, and `inverseJoinColumn` properties are only available after [Medusa v2.0.7](https://github.com/medusajs/medusa/releases/tag/v2.0.7). |
|
258
|
|
|
259
|
</Note> |
|
260
|
|
|
261
|
<Note> |
|
262
|
|
|
263
|
Following [Medusa v2.1.0](https://github.com/medusajs/medusa/releases/tag/v2.1.0), if `pivotTable`, `joinColumn`, and `inverseJoinColumn` aren't specified on either model, the owner is decided based on alphabetical order. So, in the example above, the `Order` data model would be the owner. |
|
264
|
|
|
265
|
</Note> |
|
266
|
|
|
267
|
In this example, an order is associated with many products, and a product is associated with many orders. Since the `pivotTable`, `joinColumn`, and `inverseJoinColumn` configurations are defined on the order, it's considered the owner data model. |
|
268
|
|
|
269
|
### Many-to-Many Relationship in the Database |
|
270
|
|
|
271
|
When you generate the migrations of data models that have a many-to-many relationship, the migration adds a new pivot table. Its name is either the name you specify in the `pivotTable` configuration or the inferred name combining the names of the data models' tables in alphabetical order, separating them by `_`, and pluralizing the last name. For example, `order_products`. |
|
272
|
|
|
273
|
The pivot table has a column with the name `{data_model}_id` for each of the data model's tables. It also has foreign keys on each of these columns to their respective tables. |
|
274
|
|
|
275
|
The pivot table has columns with foreign keys pointing to the primary key of the associated tables. The column's name is either: |
|
276
|
|
|
277
|
- The value of the `joinColumn` configuration for the owner table, and the `inverseJoinColumn` configuration for the owned table; |
|
278
|
- Or the inferred name `{table_name}_id`. |
|
279
|
|
|
280
|
 |
|
281
|
|
|
282
|
### Many-To-Many with Custom Columns |
|
283
|
|
|
284
|
To add custom columns to the pivot table between two data models having a many-to-many relationship, you must define a new data model that represents the pivot table. |
|
285
|
|
|
286
|
For example: |
|
287
|
|
|
288
|
export const manyToManyColumnHighlights = [ |
|
289
|
["5", "products", "Many-to-many relation to the `Product` data model."], |
|
290
|
["6", "pivotEntity", "Specify the data model representing the pivot table."], |
|
291
|
["12", "orders", "Many-to-many relation to the `Order` data model."], |
|
292
|
["15", "OrderProduct", "Data model that represents the pivot table between orders and products."], |
|
293
|
["17", "order", "Relation to the Order data model."], |
|
294
|
["20", "product", "Relation to the Product data model."], |
|
295
|
["23", "metadata", "Extra column in the pivot table."] |
|
296
|
] |
|
297
|
|
|
298
|
```ts highlights={manyToManyColumnHighlights} |
|
299
|
import { model } from "@medusajs/framework/utils" |
|
300
|
|
|
301
|
export const Order = model.define("order_test", { |
|
302
|
id: model.id().primaryKey(), |
|
303
|
products: model.manyToMany(() => Product, { |
|
304
|
pivotEntity: () => OrderProduct, |
|
305
|
}), |
|
306
|
}) |
|
307
|
|
|
308
|
export const Product = model.define("product_test", { |
|
309
|
id: model.id().primaryKey(), |
|
310
|
orders: model.manyToMany(() => Order), |
|
311
|
}) |
|
312
|
|
|
313
|
export const OrderProduct = model.define("orders_products", { |
|
314
|
id: model.id().primaryKey(), |
|
315
|
order: model.belongsTo(() => Order, { |
|
316
|
mappedBy: "products", |
|
317
|
}), |
|
318
|
product: model.belongsTo(() => Product, { |
|
319
|
mappedBy: "orders", |
|
320
|
}), |
|
321
|
metadata: model.json().nullable(), |
|
322
|
}) |
|
323
|
``` |
|
324
|
|
|
325
|
The `Order` and `Product` data models have a many-to-many relationship. To add extra columns to the created pivot table, you pass a `pivotEntity` option to the `products` relation in `Order` (since `Order` is the owner). The value of `pivotEntity` is a function that returns the data model representing the pivot table. |
|
326
|
|
|
327
|
The `OrderProduct` model defines, aside from the ID, the following properties: |
|
328
|
|
|
329
|
- `order`: A relation that indicates this model belongs to the `Order` data model. You set the `mappedBy` option to the many-to-many relation's name in the `Order` data model. |
|
330
|
- `product`: A relation that indicates this model belongs to the `Product` data model. You set the `mappedBy` option to the many-to-many relation's name in the `Product` data model. |
|
331
|
- `metadata`: An extra column to add to the pivot table of type `json`. You can add other columns as well to the model. |
|
332
|
|
|
333
|
--- |
|
334
|
|
|
335
|
## Cascades |
|
336
|
|
|
337
|
When an operation is performed on a data model, such as record deletion, the relationship cascade specifies what related data model records should be affected by it. |
|
338
|
|
|
339
|
For example, if a store is deleted, its products should also be deleted. |
|
340
|
|
|
341
|
The `cascades` method used on a data model configures which child records an operation is cascaded to. |
|
342
|
|
|
343
|
For example: |
|
344
|
|
|
345
|
export const highlights = [ |
|
346
|
["8", "", "When a store is deleted, delete its associated products."] |
|
347
|
] |
|
348
|
|
|
349
|
```ts highlights={highlights} |
|
350
|
import { model } from "@medusajs/framework/utils" |
|
351
|
|
|
352
|
const Store = model.define("store", { |
|
353
|
id: model.id().primaryKey(), |
|
354
|
products: model.hasMany(() => Product), |
|
355
|
}) |
|
356
|
.cascades({ |
|
357
|
delete: ["products"], |
|
358
|
}) |
|
359
|
|
|
360
|
const Product = model.define("product", { |
|
361
|
id: model.id().primaryKey(), |
|
362
|
store: model.belongsTo(() => Store, { |
|
363
|
mappedBy: "products", |
|
364
|
}), |
|
365
|
}) |
|
366
|
``` |
|
367
|
|
|
368
|
The `cascades` method accepts an object. Its key is the operation’s name, such as `delete`. The value is an array of relationship property names that the operation is cascaded to. |
|
369
|
|
|
370
|
In the example above, when a store is deleted, its associated products are also deleted. |
|
371
|
|
|
372
|
--- |
|
373
|
|
|
374
|
## Searchable Relationships |
|
375
|
|
|
376
|
You can make relationship properties searchable by adding the `searchable` method to any relationship definition (`hasMany`, `hasOne`, `belongsTo`, or `manyToMany`). |
|
377
|
|
|
378
|
When a relationship property is marked as searchable, the related records' searchable text properties can be queried when using the `q` filter in service methods like `list{ModelName}s`. |
|
379
|
|
|
380
|
For example: |
|
381
|
|
|
382
|
export const searchableRelationshipHighlights = [ |
|
383
|
["7", "searchable", "Make the products relationship searchable."], |
|
384
|
["12", "searchable", "Make the title property of the product searchable."] |
|
385
|
] |
|
386
|
|
|
387
|
```ts highlights={searchableRelationshipHighlights} |
|
388
|
import { model } from "@medusajs/framework/utils" |
|
389
|
|
|
390
|
const Store = model.define("store", { |
|
391
|
id: model.id().primaryKey(), |
|
392
|
products: model.hasMany(() => Product, { |
|
393
|
mappedBy: "store", |
|
394
|
}).searchable(), |
|
395
|
}) |
|
396
|
|
|
397
|
const Product = model.define("product", { |
|
398
|
id: model.id().primaryKey(), |
|
399
|
title: model.text().searchable(), |
|
400
|
store: model.belongsTo(() => Store, { |
|
401
|
mappedBy: "products", |
|
402
|
}), |
|
403
|
}) |
|
404
|
``` |
|
405
|
|
|
406
|
In this example, when you search for stores using the `q` filter, the search will include matching product titles from the related products. |