How to do raw query in Bookshelf.js

空扰寡人 提交于 2019-12-21 11:34:08

问题


I want to achieve this

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

from https://developers.google.com/maps/articles/phpsqlsearch_v3?hl=fr#createtable

How can I make this query with Bookshelf.

I have this now:

var raw = '( 3959 * acos( cos( radians(37) ) * cos( radians( '+ req.params.lat + ' ) ) * cos( radians( '+req.params.lng+' ) - radians(-122) ) + sin( radians(37) ) * sin( radians( '+req.body.lng+' ) ) ) ) AS distance';


new Places().query(function(qb) {
    qb.where('lat',req.params.lat); 
    qb.where('lng',req.params.lng); 
    qb.column(raw);
    qb.having('distance', '>', 25);
}).fetch({ debug: false }).then(function(collection) {
    console.log(collection);

    if (collection === undefined) {
        // no such result
        res.json(404,{error: "No Places found."});
    } else {
        // found, list json
        res.json(200, collection);
    }
});

回答1:


I found this to work .. no qb. instance/reference required:

var Bookshelf = require('bookshelf').mysqlAuth;

var rawSql = 'SELECT .. <etc>';

Bookshelf.knex.raw(rawSql).then(..);



回答2:


Its.

qb.column(qb.knex.raw(raw));



回答3:


i Tried something like this which worked fine

return **Location**.query(qb => {
      return ***query***
    })
    .fetchAll()
    .then(data => data.toJSON());

With:

  • Location is a Model (I am doing it inside strapi services)

  • query can be any raw query.



来源:https://stackoverflow.com/questions/23952960/how-to-do-raw-query-in-bookshelf-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!