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
})
})
})
You need to use join
to use multiple tables on the basis of some reference key
Here is example
of join two tables at with reference key
table 1:users And table2: accounts
And reference key is user's primary key
.then(function() {
return knex('users')
.join('accounts', 'users.id', 'accounts.user_id')
.select('users.user_name as user', 'accounts.account_name as account');
})
Hope this can give you better idea.
For more reference see the Docs
I found the solution, to the problem and it is working, just adding a new query to the .then of the previous one and passing it as an argument so I can render both tables to the same .html and use them independently.
knex.select()
.from('schools')
.then(function(schools){
knex.select()
.from('students')
.then(function(students) {
res.render('schools', {
students: students,
schools: schools
});
});
}).catch(function(error) {
console.log(error);
});
来源:https://stackoverflow.com/questions/39631240/query-multiple-tables-with-knex-js