0

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

我的模型是:

发布.js

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

工作表.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() 方法之外,我还想对填充的数据运行一些查找命令,以获取工作表名称也与某个键匹配的那些出版物。

4

1 回答 1

0

基本上,您要做的是查询关联的属性。自 2014 年以来,这一直在水线路线图中,但仍不受支持,因此您必须找出解决方法。

一种选择是查询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)

或者,您可以将Worksheetand组合Publication成一个模型,因为它们是一对一的。可能并不理想,但是sails.js 和Waterline 使得处理关系数据变得非常困难——我估计我正在处理的项目中的一半查询是原始查询,因为sails 对postgres 的支持很差。该框架非常偏向于使用 MongoDB,尽管它声称可以与任何“支持的”数据库“正常工作”

于 2017-05-15T22:48:06.577 回答