What's the benefit of defining BelongsTo relation?
When I defined HasMany
relation I could execute all my queries without missing anyone (I prefer to give me an example in case you find it's important to use BelongsTo
relation).
The benefit is being able to flip the "base" and "child" in of the relation. LoopBack 4 relation filters are akin to an SQL LEFT JOIN, meaning that the filter must be scoped from the base model.
From the "Filtering by parent model" docs:
Where filters such as those used by model queries (
create()
,find()
,replaceById()
, and so on) cannot be used to filter a model by the value of its parent model. See its GitHub issue.
For example, we may have many Orders made by a Customer:
@hasMany(() => Order)
orders?: Order[];
This relation enables querying for "orders made by a customer" or "orders made by a list of filtered customers", but not the other way around; "the customer that made that order" or "the customers that made a list of filtered orders".
A Belongs To relation solves this by creating a key on the Order that references a Customer:
@belongsTo(() => Customer)
customerId: number;
This means that we can now query "which customer made that order" or "which customers made the filtered list of orders".
Another important factor is that a Has Many relation can't be made into a Strong Relation as ANSI SQL does not have a method of representing such relations. From the docs:
LoopBack 4 implements weak relations with
@belongsTo()
,@hasMany()
,@hasOne()
, etc. This means the constraints are enforced by LoopBack 4 itself, not the underlying database engine. This is useful for integrating cross-database relations, thereby allowing LoopBack 4 applications to partially take the role of a data lake.However, this means that invalid data could be keyed in outside of the LoopBack 4 application. To resolve this issue, some LoopBack 4 connectors (such as PostgreSQL and MySQL) allow defining a foreign key constraint through the
@model()
decorator. Please consult the respective connector documentation to check for compatibility.
Emphasis in italics is mine on why these restrictions apply.