【问题标题】:Using Objection JS How can I select specific columns with withGraphFetched使用 Objection JS 如何使用 withGraphFetched 选择特定列
【发布时间】:2021-02-16 00:42:28
【问题描述】:

我有一个问题: 如何使用withGraphFetched 方法指示我想从数据库中获取哪些列,我有一个BelongsToOneRelation,我想排除一些列,这是我的模型:

module.exports = class ProveedorModel extends Model {

  ...

  static relationMappings = {
    empresa: {
      relation: Model.BelongsToOneRelation,
      modelClass: EmpresaModel,
      join: {
        from: 'proveedor.empresa_id',
        to: 'empresa.id'
      }
    }
  };

  ...

}

在我的控制器中我有这个:

const payload = await ProveedorModel.query().withGraphFetched('empresa');

但是表empresa 有很多我不会的列,那么我该如何过滤?

【问题讨论】:

    标签: mysql orm objection.js


    【解决方案1】:

    您可以为您的关系指定filter 属性

    class Person extends Model {
      static relationMappings = {
        pets: {
          relation: Model.OneToManyRelation,
          modelClass: Animal,
          filter: query => query.select('id', 'ownerId', 'name'),
          join: {
            from: 'Person.id',
            to: 'Animal.ownerId'
          }
        }
      }
    }
    

    参考:https://github.com/Vincit/objection.js/issues/70#issuecomment-175143072

    只是想知道为什么在使用 withGraphFetched 时,反对不只查询映射在 tableMetadata (https://vincit.github.io/objection.js/api/model/static-methods.html#static-tablemetadata) 中的列,就像它对 withGraphJoined 所做的那样

    或者,您可以使用 parsedatabasejson 仅映射您想要的属性 (https://vincit.github.io/objection.js/api/model/instance-methods.html#parsedatabasejson) 但您的 SQL 查询将把它们全部带入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多