【问题标题】:How to fetch hasMany relation in BookShelf.js如何在 BookShelf.js 中获取 hasMany 关系
【发布时间】:2020-05-19 18:29:30
【问题描述】:

我正在尝试从与投资模型具有“hasMany”关系的 Offer 模型中获取数据,但我总是收到错误 “必须为 offer hasMany 关系定义有效的目标模型”强>

报价型号:

const Investment = require('./investment')

const Offer = bookShelfDatabase.Model.extend({
    tableName: 'offers',
    investment: function() {
        return this.hasMany(Investment);
      }
});

module.exports = Offer;

投资模式:

const Offer = require('./offer');


const Investment = bookShelfDatabase.Model.extend({
    tableName: 'investments',
    offers: function () {
        return this.belongsTo(Offer, 'offer_id');
      }
});

module.exports = Investment;

我的服务

const offers = await new Offer({ id: 1 }).fetchAll({
      withRelated: [
        {
          'investment': function (qb) {
            qb.select("id");
          },
        },
      ],
    });

【问题讨论】:

    标签: javascript node.js database orm bookshelf.js


    【解决方案1】:

    你有一个循环依赖问题。 Offer 需要 Investment 和 Investment 需要 Offer,这是行不通的。

    使用推荐的创建模型的方法 (.model()) 而不是 .extend(),你会没事的:https://bookshelfjs.org/tutorial-models.html

    【讨论】:

    • 我将创建模型的方式更改为.model(),就像你说的那样,但我仍然遇到同样的错误
    • 您还需要删除 require 行并仅使用模型名称,例如:this.hasMany('Investment')。
    猜你喜欢
    • 2020-04-29
    • 1970-01-01
    • 2015-11-29
    • 2023-03-31
    • 2014-04-19
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多