`BelongsTo` 关系有什么好处?

What's the benefit of `BelongsTo` relation?

定义 BelongsTo 关系有什么好处?

当我定义 HasMany 关系时,我可以执行所有查询而不会遗漏任何人(我更愿意给我一个例子,以防您发现使用 BelongsTo 关系很重要)。

好处是能够翻转关系中的“基”和“子”。 LoopBack 4 关系过滤器类似于 SQL LEFT JOIN,这意味着过滤器必须在基本模型范围内。

来自"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.

例如,我们可能有一个客户下的许多订单:

@hasMany(() => Order)
orders?: Order[];

此关系可以查询“客户下的订单”或“过滤后的客户列表下的订单”,但反之则不行; “下订单的客户”或“制作过滤订单列表的客户”。

Belongs To 关系通过在引用客户的订单上创建键来解决此问题:

@belongsTo(() => Customer)
customerId: number;

这意味着我们现在可以查询“哪个客户下了那个订单”或“哪个客户下了过滤后的订单列表”。


另一个重要的因素是,Has Many 关系不能变成强关系,因为 ANSI SQL 没有表示这种关系的方法。来自 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.

我用斜体强调这些限制为何适用。