Execute raw query on MySQL Loopback Connector

北慕城南 提交于 2019-11-30 07:12:27

Here is a basic example. If you have a Product model (/common/models/product.json), extend the model by adding a /common/models/product.js file:

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 }
        }
    );

};

This will create the following endpoint example: GET /Products/byCategory?group=computers

http://docs.strongloop.com/display/public/LB/Executing+native+SQL

  1. expose a remote method in your /common/models/model.js
  2. execute the sql query in the remote method (via dataSource.connector.query(sql, cb);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!