簡體   English   中英

加入 bookshelf.js

[英]Join in bookshelf.js

我如何在 bookshelf.js 中實現以下關系

SELECT user_accounts.user_id,  `event_id` 
FROM  `calendar_events` 
JOIN user_accounts ON user_accounts.user_id = calendar_events.`created_by` 
LIMIT 10

我的模特

var CalendarEvent = bookshelf.Model.extend({
    tableName: 'calendar_events',
    hasTimestamps: ['created_on'],
    user: function() {
        return this.hasOne('UserAccount','user_id');
    }
});

var UserAccount = bookshelf.Model.extend({
    tableName: 'user_account'
});

如果您想獲得確切的樣式查詢,您可以使用 knex 查詢構建器並嘗試構建一個查詢以滿足您的需求

沒有測試過這個,但應該是這樣的

CalendarEvent.forge().query(function(qb){
  qb.join('user_accounts', 'user_accounts.user_id', '=', 'calendar_events.created_by');
  //qb.where() //if you wanted
  //qb.andWhere();  //and if you wanted more
  qb.limit(10);

})    
.fetchAll();

(你不需要 .where 或 .andWhere,只是為了好玩而添加的)

完全可以在書架上完成,但我現在不確定如何。

我想您自 2016 年以來就找到了解決方案,但這是答案

var CalendarEvent = bookshelf.Model.extend({
    tableName: 'calendar_events',
    hasTimestamps: ['created_on'],
    user: function() {
        return this.belongsTo(UserAccount, 'user_id', 'created_by');
    }
});

var UserAccount = bookshelf.Model.extend({
    tableName: 'user_account'
});

使用belongsTo() 方法,因為外鍵在CalendarEvent 模型中而不是在UserAccount 模型中。 將外鍵的名稱附加到belongsTo() 參數以指定外鍵的名稱。

然后,像這樣使用書架模型:

CalendarEvent
    .forge()
    .fetchPage({ pageSize: 10, withRelated: ['user'] })
    .then(data => {
        // Data retrieval
    })
    .catch(exc => {
        // Error management
    });

fetchPage 方法使用pagepageSize創建分頁。 您將檢索包含行信息(行數、頁碼、頁面大小、頁面總數)的data.pagination對象,而data.toJSON()將檢索您的模型。

暫無
暫無

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

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