在 Objection.js 中,设置关系映射有什么好处?

Are*_*Lin 4 objection.js

我对关系映射在 Objection.js 模型类中的作用感到有点困惑。

我想一旦我们在模型中设置了关系映射,我们就会在每个查询中获得相关数据。但是,事实证明我仍然只有模型属性本身。

我还应该使用其他什么方法来获取查询中的相关数据吗?

Mik*_*stö 7

关系映射提供了模型语义,以便在需要时如何获取关系。除了主表的行之外,始终查询所有相关行对性能来说确实很糟糕。当您创建到模型的关系映射时,您不需要每次需要查询关系时都手动编写联接。它们还启用了许多其他对象功能,这需要了解行关系在数据库中的变化方式。

.withGraphFetched要在查询 Objection.js 中使用关系映射,要求在每个查询中,您必须使用或.withGraphJoined方法告诉主行要获取哪些关系https://vincit.github.io/objection.js/guide/query-examples。 html#渴望加载

例如:

class Person extends Model {
  static get tableName() {
    return 'persons';
  }

  static get relationMappings() {
    return {
      pets: {
        relation: Model.HasManyRelation,
        modelClass: Animal,
        join: {
          from: 'persons.id',
          to: 'animals.ownerId'
        }
      }
    };
  }
}


const people = await Person.query().withGraphFetched('pets');

// Each person has the `pets` property populated with Animal objects related
// through the `pets` relation.
console.log(people[0].pets[0].name);
console.log(people[0].pets[0] instanceof Animal); // --> true
Run Code Online (Sandbox Code Playgroud)

当您插入嵌套对象数据时,也会使用映射.insertGraph,以便将相关对象插入到相关表中,并根据关系映射声明自动填充外键引用等。

还有很多其他地方使用它们,但我希望这能让您大致了解它们存在的原因。