簡體   English   中英

用knex.js查詢多個表

[英]query multiple tables with knex.js

我想使用Expres.jsknex.js渲染兩個表,僅使用一個get函數,以便在一個HTML模板中使用兩個表中的數據。 當我僅查詢一個表(學校或學生)但不知道如何處理兩個表時,此方法有效。 有什么建議嗎?

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);
    });
});

您需要使用join才能在某個reference key的基礎上使用多個表。這是在兩個表之間使用參考鍵進行連接的example

表1: 用戶和表2: 帳戶

而參考鍵是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');
})

希望這可以給您更好的主意。

有關更多參考,請參閱文檔

您的方法確實有效,但是我建議您使用這種習慣用法,以避免promise地獄 (有關更多示例,請參閱鏈接。)

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
    })
  })
})

我找到了解決該問題的解決方案,並且該解決方案正在起作用,只需將新查詢添加到上一個查詢的.then中並將其作為參數傳遞,這樣我就可以將兩個表呈現為相同的.html並獨立使用它們。

    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);
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM