【问题标题】:Sort populated record in sails waterline对风帆水线中的填充记录进行排序
【发布时间】:2016-10-07 20:20:01
【问题描述】:

我创建了一个带有两个模型 Publication 和 Worksheet 的 Sails 应用程序。他们是一对一的关系。 Sails-postgresql 是我正在使用的适配器。我正在使用水线 orm 对数据库进行查询。我在尝试将出版物数据与工作表一起加载,然后使用 sort() 根据工作表中的字段对记录进行排序时出现错误。

我的模型是:

Publication.js

module.exports = {
  attributes: {
       id: {
          type: 'integer'
          unique: true
        },
        worksheetId: {
          type: 'integer',
          model : 'worksheet'
        },
        status: {
          type: 'string',
          defaultsTo: 'active',
          in : ['active', 'disabled'],
        }
  }
}

Worksheet.js

module.exports = {
   attributes: {
      id: {
         type: 'integer',
         unique: true
      },
      name: 'string',
      orderWeight: {
         type: 'integer',
         defaultsTo: 0
      }
  }
}

所以现在我想加载所有状态为“活动”的出版物并在数据中填充工作表。

所以我正在执行查询:

Publication.find({
  where: {
    status: 'active'
  }
})
.populate('worksheetId').limit(1)
.exec(function (error, publications) {
})

我得到的数据如下:

{
   id : 1,
   status : "active",
   worksheetId : {
      id : 1
      name : "test",
      orderWeight : 10
   }
}

所以到目前为止一切正常。现在我想将限制增加到 10,并希望根据填充数据中的“orderWeight”对数据进行排序。最初,我根据发布 ID 对整个数据进行排序,并且查询有效。

Publication.find({
  where: {
    status: 'active'
  }
})
.populate('worksheetId').sort('id ASC').limit(10)
.exec(function (error, publications) {
})

所以我触发了类似的查询来对“orderWeight”上的数据进行排序

Publication.find({
   where: {
      status: 'active'
   }
})
.populate('worksheetId').sort('worksheetId.orderWeight ASC').limit(10)
.exec(function (error, publications) {
})

这个查询给了我一个错误,即 worksheetId.orderWeight 不是发布表上的列。所以我想对不在发布表上的填充数据触发这种排序查询。

请告诉我如何才能获得预期的结果。

除了 sort() 方法之外,我还想对填充的数据运行一些查找命令,以获取工作表名称也与某个键匹配的那些发布。

【问题讨论】:

    标签: postgresql waterline populate sails-postgresql


    【解决方案1】:

    基本上,您要做的是查询关联的属性。 This has been in the waterline roadmap since 2014, but it's still not supported,所以你必须想出一个解决方法。

    一种选择是查询Worksheet 模型并填充Publication,因为sails 不允许您在不使用原始查询的情况下跨模型进行查询(即.sort('worksheetId.orderWeight ASC') 不起作用)。不幸的是,您可能必须将active 标志移动到Worksheet。例如:

    Worksheet.find({
      status: 'active'
    })
    .populate('publication') // you should also add publication to Worksheet.js
    .sort('orderWeight ASC')
    .limit(10)
    

    或者,您可以将WorksheetPublication 组合成一个模型,因为它们是一对一的。可能并不理想,但是sails.js 和Waterline 使得处理关系数据变得非常困难——我估计我正在处理的项目中的一半查询是原始查询,因为sails 对postgres 的支持很差。该框架非常倾向于使用 MongoDB,although it claims to "just work" with any of the "supported" DBs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-11
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      相关资源
      最近更新 更多