使用Bookshelfjs的M-N关系

时间:2017-11-23 07:53:47

标签: knex.js bookshelf.js

如何使用bookshelfjs从联结表查询主表。 这是我的查询

SELECT 
  a.id,
  current_store_type_id,
  b.code as current_store_type_code,
  new_store_type_id, 
  c.code as new_store_type_code
FROM 
  store_upgrade a
JOIN lt_store_type b
ON a.current_store_type_id = b.id
JOIN lt_store_type c
ON a.new_store_type_id = c.id
WHERE 1 = 1;

请检查我的these directions。为了您的信息,我正在使用Postgres

1 个答案:

答案 0 :(得分:0)

Bookshelf旨在查询数据库以获取嵌套对象。以下是使用Bookshelf查询数据库所需的模型。

var StoreType = bookshelf.Model.extend({
    tableName: 'lt_store_type'
});

var StoreUpgrade = bookshelf.Model.extend({
    tableName: 'store_upgrade',

    currentStore: function() {
        return this.belongsTo(StoreType, 'current_store_type_id');
    },
    newStore: function() {
        return this.belongsTo(StoreType, 'new_store_type_id');
    }
});

用于获取数据的Bookshelf方法

StoreUpgrade
    .forge()
    .fetchAll({ withRelated: ['currentStore', 'newStore'] })
    .then(data => {
        // Data retrieval
    })
    .catch(exc => {
        // Error management
    });

这是你得到的输出

[
    {
        id: 1,
        currentStore: {
            id: 2,
            code: "KIWI"
        },
        newStore: {
            id: 3,
            code: "DURIAN"
        }
    },
    {
        id: 2,
        currentStore: {
            id: 1,
            code: "BANANA"
        },
        newStore: {
            id: 2,
            code: "KIWI"
        }
    }
]
相关问题