我使用 knexnest 的方式如下:
const customerProducts = knex.select([
'CustomerProduct.id AS _id',
'CustomerProduct.price AS _price',
'CustomerProduct.active AS _active',
'CustomerProduct.customer_id AS _customerId',
'CustomerProduct.product_id AS _productId',
'customer.id AS _customer_id',
'customer.name AS _customer_name',
])
.from('customer_products AS CustomerProduct')
.innerJoin(
'customers AS customer',
'CustomerProduct.customer_id',
'customer.id',
)
.where(whereClause);
const result = knexnest(customerProducts).then(data => data);
return result;
我可能会创建几个其他查询,然后使用 knexnest 创建嵌套模型。有什么办法可以拉knexnest(customerProducts).then(data => data);
到另一个文件中,这样我就可以调用它,而不是在每个查询中添加该行,并且还必须将 knexnest 导入到每个文件中?
要实现您想要实现的目标,最简单的方法是导出一个返回由 knexnest
生成的 Promise 的函数。然后,在主文件中导入该函数并调用它。您可以使用 async/await 语法糖或 .then
。在整个应用程序中使用一个 knex 连接对象来利用 knex 的连接池非常重要。因此,我们必须将其传递到您的函数中,以便其他文件可以访问已建立的连接对象。
文件 1
const Knex = require('knex');
// import the function getCustomerProducts using destructuring
const { getCustomerProducts } = require('<File 2's Path>');
// initialize knex & set up knex database connection
const knex = Knex({
client: 'postgres',
connection: process.env.DATABASE_URL
});
// pseudo-code - note: await can only be called within an async function
// pass knex connection object into function to leverage knex's connection pooling
const products = await getCustomerProducts(knex);
文件2
const knexnest = require('knexnest');
const getCustomerProducts = knex => {
const customerProducts = knex.select([
'CustomerProduct.id AS _id',
'CustomerProduct.price AS _price',
'CustomerProduct.active AS _active',
'CustomerProduct.customer_id AS _customerId',
'CustomerProduct.product_id AS _productId',
'customer.id AS _customer_id',
'customer.name AS _customer_name',
])
.from('customer_products AS CustomerProduct')
.innerJoin(
'customers AS customer',
'CustomerProduct.customer_id',
'customer.id',
)
.where(whereClause);
return knexnest(customerProducts);
};
// named export of the function getCustomerProducts
module.exports.getCustomerProducts = getCustomerProducts;
我是一名优秀的程序员,十分优秀!