Objection.js 查询构建器如何知道何时应该执行链式调用?

Ram*_*aro 4 node.js knex.js objection.js

正如文档中的示例所示

await User.query()返回一个包含用户数组的承诺。

await User.query().findById(1)返回 ID 为 1 的用户。

如何知道User.query()何时需要执行它或者它是否被链接。

我假设一旦User.query()被调用,请求就已经传输到数据库服务器,因此无法修改。但是,将其链接起来.findById(1)会修改请求,以便它使用条件 where 构建查询User.id = 1;,然后将其传输到数据库服务器?。这是如何运作的?

Mik*_*stö 5

User.query()返回一个查询生成器,其中可以添加任意数量的链式方法调用:

\n
query = User.query();\nquery.where('id', 1);\nquery.limit(1);\n\n// also each method returns `this` as return value so chaining is possible\n\nquery.select('id', 'name').where('name', 'like', '%batman%')\n\n
Run Code Online (Sandbox Code Playgroud)\n

现在查询已完成,您希望执行查询构建器并将查询发送到您需要调用的数据库.then(),或者例如通过Promise.resolve(query)隐式调用查询构建器的.then方法来解析它。

\n

在您的情况下,您正在使用await触发查询,该查询实际上只是 \xc2\xb4Promise.resolve` 的语法糖

\n

以下所有执行查询的示例几乎都是等效的

\n
\n// await with parenthesis underlining execution order of statements\nres = await (User.query().select('name'));\n\n// await without parenthesis with implicit execution order\nres = await User.query().select('name');\n\n// older way with thenables and promises\nUser.query().select('name').then(res => {\n})\n\n// another way with themables and promises\nPromise.resolve(User.query().select('name')).then(res => {\n\n})\n\n
Run Code Online (Sandbox Code Playgroud)\n

因此,上述所有情况都会调用.then查询构建器的方法来执行查询并.then返回一个承诺,该承诺将使用从数据库读取的结果来解析。

\n