knex 单表查询_用knex.js查询多个表

I want to render with Expres.js and knex.js two tables using for that only one get function in order to use the data from both tables in one HTML template. It works when I query only one table (schools or students) but I don't know how to do with two tables.

Any suggestion?

app.get('/schools', function(req, res) {

knex.select()

.from('schools', 'students')

.then(function(schools, students) {

res.render('schools', {

schools: schools,

students: students

});

}).catch(function(error) {

console.log(error);

});

});

解决方案

your approach indeed works, however i suggest you this idiom in order to avoid the promise hell (see the link for even better examples.)

router.get("/schools",function(req,res){

var schools

knex("schools").select().then(function(ret){

schools=ret

return knex("students").select()

}).then(function(students){

res.render("schools",{

students: students,

schools: schools

})

})

})

要使用 knex.js,您需要按照以下步骤进行设置和使用: 1. 首先,确保您的项目已经安装了 Node.js,并且已经创建了一个新的项目文件夹。 2. 在项目文件夹中打开终端,并执行以下命令来初始化项目并安装 knex.js: ``` npm init -y npm install knex --save ``` 3. 接下来,您需要选择一个数据库驱动程序来与 knex.js 一起使用。例如,如果您想使用 MySQL,可以执行以下命令来安装相应的驱动程序: ``` npm install mysql --save ``` 4. 在项目文件夹中创建一个 `knexfile.js` 文件,用于配置 knex.js。在该文件中,您需要指定数据库的连接信息和其他选项。以下是一个 MySQL 数据库的示例配置: ```javascript module.exports = { development: { client: 'mysql', connection: { host: 'localhost', user: 'your_username', password: 'your_password', database: 'your_database' } }, // 可以添加其他环境配置,如 production、test 等 }; ``` 5. 创建一个新的 JavaScript 或 TypeScript 文件,并在其中初始化 knex。您可以使用以下代码示例: ```javascript const knex = require('knex'); const config = require('./knexfile'); // 根据环境选择合适的配置 const environment = process.env.NODE_ENV || 'development'; const knexInstance = knex(config[environment]); // 现在您可以使用 knexInstance 进行数据库操作了 knexInstance.select().from('users').then((rows) => { console.log(rows); }).finally(() => { knexInstance.destroy(); }); ``` 请注意,上述代码中的 `users` 是数据库中的名,您可以根据自己的实际情况进行修改。 这只是一个简单的使用示例,knex.js 还提供了许多其他功能和方法,例如创建、插入数据、更新数据等。您可以查阅 knex.js 的官方文档以了解更多信息和示例:https://knexjs.org/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值