【发布时间】:2016-05-19 02:19:05
【问题描述】:
如何通过带有强循环的 REST API 执行原始查询并公开结果?
我已经阅读了一些关于使用 hooks 和 dataSource.connector.query() 的内容,但我找不到任何工作示例。
【问题讨论】:
标签: mysql node.js loopbackjs strongloop
如何通过带有强循环的 REST API 执行原始查询并公开结果?
我已经阅读了一些关于使用 hooks 和 dataSource.connector.query() 的内容,但我找不到任何工作示例。
【问题讨论】:
标签: mysql node.js loopbackjs strongloop
这是一个基本示例。如果您有产品模型 (/common/models/product.json),请通过添加 /common/models/product.js 文件来扩展模型:
module.exports = function(Product) {
Product.byCategory = function (category, cb) {
var ds = Product.dataSource;
var sql = "SELECT * FROM products WHERE category=?";
ds.connector.query(sql, category, function (err, products) {
if (err) console.error(err);
cb(err, products);
});
};
Product.remoteMethod(
'byCategory',
{
http: { verb: 'get' },
description: 'Get list of products by category',
accepts: { arg: 'category', type: 'string' },
returns: { arg: 'data', type: ['Product'], root: true }
}
);
};
这将创建以下端点示例:GET /Products/byCategory?group=computers
http://docs.strongloop.com/display/public/LB/Executing+native+SQL
【讨论】:
Product.byGroup 应该是Product.byCategory 和"SELECT * FROM products 应该是"SELECT * FROM products
Product 然后插入
This feature has not been fully tested and is not officially supported: the API may change in future releases. In general, it is always better to perform database actions through connected models. Directly executing SQL may lead to unexpected results, corrupted data, and other issues. 为什么文档会这样说明?
/common/models/model.js 中公开一个远程方法
dataSource.connector.query(sql, cb);
【讨论】: