如何在书架中执行 SQL 查询

How to execute SQL query in bookshelf

有人知道如何在书架中执行 SQL 查询吗? 类似于:

bookshelf.query(sql).then(function(results) {
    callback(null, results);
});

您不能在 Bookshelf.js 中执行原始查询。如果你愿意,可以这样使用 Knex.js(Bookshelf 使用):

const myId = 42;
knex.raw('SELECT * FROM MyTable WHERE id = ?', [myId])
.then(result => {
    console.log(result);
}, error => {
    console.log(error);
});

Bookshelf.js 是一个 ORM,您在 Javascript 项目中声明每个 table 并使用这些模型从数据库中检索数据。

举个例子。

const Company = db.bookshelf.Model.extend({
    tableName: 'companys',
    hunters: function employees() {
        return this.hasMany(Employee, 'company_id');
    }
});

const Employee = db.bookshelf.Model.extend({
    tableName: 'employees',
    company: function company() {
        return this.belongsTo(Company);
    }
});

Company.where({ id: 42 }).fetch([ withRelated: 'employees' ])
.then(result => {
    console.log(result);
}, error => {
    console.log(error);
})