Bookshelfjs ORM 如何获取或查看 SQL 声明其构建

Bookshelfjs ORM How to get or see SQL statement its building

构建 ORM 查询时,我想查看执行的实际(原始)查询是什么。

例如在Rails中我们可以这样做:

User.where(name: 'Oscar').to_sql
# => SELECT "users".* FROM "users"  WHERE "users"."name" = 'Oscar'

Bookshelfjs 中有此功能吗?或任何其他方式获得这个?

提前致谢

看起来没有直接的方法来获取 SQL 语句,例如 Rails produce..

您可以改用 .query() .toSQL() or .query() .toString(). But achieving exact result as in Rails is a bit more complicated as queries may be not complete. The cause is that many statements get applied just before performing the query in Bookshelf. For example Bookshelf relations behave so. Also many plugins use events to apply query statements. If you want to debug the queries then I would suggest you to use Knex#debug。例如

model.query(function(qb) {
  qb.debug(true);
}).fetch()

它在控制台中打印调试信息。

来源:来自官方bookshelfjs github