Relations
Rest Faker supports defining relationships between your data models. Relations determine how records from different routes are linked and how nested data is returned in API responses.
belongsTo
A record belongs to another record. Adds a foreign key field (e.g., postId) to the child model.
hasMany
A record has many related records. Returns a nested array of related items in the response.
hasOne
A record has exactly one related record. Returns a nested object in the response.
belongsTo
Use belongsTo when a record references a parent record. For example, a Comment belongs to a Post. This adds a foreign key field to the child record.
// A "comments" route configured with belongsTo "posts"
// Each comment record will include a postId field
// GET /api/schema/comments
{
"data": [
{
"id": "c1a2b3c4-...",
"body": "Great article!",
"postId": "d9c03940-8451-4c3e-944f-6ddfd23390f6",
"createdAt": "2025-01-15T11:00:00Z",
"updatedAt": "2025-01-15T11:00:00Z"
}
],
"meta": { "total": 25, "page": 1, "perPage": 10, "pages": 3 }
}hasMany
Use hasMany when a record owns multiple related records. For example, a Post has many Comments. The related records are returned as a nested array.
// A "posts" route configured with hasMany "comments"
// Each post record will include a nested comments array
// GET /api/schema/posts/d9c03940-8451-4c3e-944f-6ddfd23390f6
{
"id": "d9c03940-8451-4c3e-944f-6ddfd23390f6",
"title": "Lorem ipsum dolor sit amet",
"description": "Consectetur adipiscing elit...",
"comments": [
{
"id": "c1a2b3c4-...",
"body": "Great article!",
"postId": "d9c03940-8451-4c3e-944f-6ddfd23390f6",
"createdAt": "2025-01-15T11:00:00Z",
"updatedAt": "2025-01-15T11:00:00Z"
},
{
"id": "e5f6a7b8-...",
"body": "Thanks for sharing.",
"postId": "d9c03940-8451-4c3e-944f-6ddfd23390f6",
"createdAt": "2025-01-15T12:00:00Z",
"updatedAt": "2025-01-15T12:00:00Z"
}
],
"createdAt": "2025-01-15T10:30:00Z",
"updatedAt": "2025-01-15T10:30:00Z"
}hasOne
Use hasOne when a record has exactly one related record. For example, a User has one Profile. The related record is returned as a nested object.
// A "users" route configured with hasOne "profile"
// Each user record will include a nested profile object
// GET /api/schema/users/a1b2c3d4-...
{
"id": "a1b2c3d4-...",
"firstName": "John",
"lastName": "Doe",
"profile": {
"id": "p1q2r3s4-...",
"bio": "Software developer and writer",
"avatar": "https://example.com/avatar.jpg",
"userId": "a1b2c3d4-...",
"createdAt": "2025-01-15T10:30:00Z",
"updatedAt": "2025-01-15T10:30:00Z"
},
"createdAt": "2025-01-15T10:30:00Z",
"updatedAt": "2025-01-15T10:30:00Z"
}Configuring Relations
Relations are configured in the Route Creator when defining your data model. Select the relation type and the target route to establish the link. The foreign key fields and nested data are handled automatically by Rest Faker.