【问题标题】:M-N relationship using Bookshelfjs使用 Bookshelfjs 的 M-N 关系
【发布时间】:2017-11-23 07:53:47
【问题描述】:

如何使用 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;

请查看我的sqlfiddle。为了您的信息,我正在使用 Postgres

【问题讨论】:

    标签: knex.js bookshelf.js


    【解决方案1】:

    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"
            }
        }
    ]
    

    【讨论】:

    • 但这会产生三个单独的查询。我如何将它们全部加入一个班轮
    • Bookshelf 将生成一个包含嵌套存储对象的对象数组,其中 knex 将生成一个包含同一对象中多个表的列的平面行数组。如果您只需要一个查询,则需要 knex 而不是 Bookshelf。 Bookshelf 并不意味着进行原始查询。它是一个 ORM,旨在帮助您查询数据库并使用嵌套对象和基于上下文的对象获取对象。多个查询有什么问题?
    • 感谢您的澄清。然后我将开始使用 knex
    猜你喜欢
    • 1970-01-01
    • 2014-11-08
    • 2015-01-05
    • 1970-01-01
    • 2018-08-18
    • 2018-05-02
    • 2022-10-25
    • 1970-01-01
    • 2019-10-05
    相关资源
    最近更新 更多