如何使用书架js输出1对多对象

How to output a 1 to many object using bookshelf js

我正在使用 bookshelf 和 knex 连接到 PostgreSQL 数据库。我正在尝试检索具有一对多关系的数据。我的数据库如下所示:

Table:运动员

|----------------------------|
|  id | firstname | lastname |
|----------------------------|
|  0  | john      | doe      |
|  1  | jane      | doe      |
|----------------------------|

Table: activity

|------------------------------------|
|  id | athlete_id | type | distance |
|------------------------------------|
|  0  |     1      | run  |    5     |
|  1  |     0      | walk |    7     |
|------------------------------------|

我的书架模型是这样的:

const Athlete = bookshelf.Model.extend({
    tableName: 'athlete',
    activities: function() {
        return this.hasMany('Activity', 'athlete_id');
    }
});

const Activity = bookshelf.Model.extend({
    tableName: 'activity',
    athlete: function() {
        return this.belongsTo('Athlete');
    }
});

然后我打电话给Activity.fetchAll().then(...)

这个returns

[
  {
    "id": "0",
    "athlete_id": "1",
    "type": "run",
    "distance": "5",
  },
  {
    "id": "1",
    "athlete_id": "0",
    "type": "walk",
    "distance": "7",
  }
]

我想要的 return 是

[
  {
    "id": "0",
    "athlete": {
        "athlete_id": "1",
        "firstname": "jane",
        "lastname": "doe"
    },
    "type": "run",
    "distance": "5",
  },
  {
    "id": "1",
    "athlete": {
        "athlete_id": "0",
        "firstname": "john"
        "lastname": "doe"
    },
    "type": "walk",
    "distance": "7",
  }
]

我发现了这个:Activity.fetch({withRelated: 'athlete'}).then(...) 但是 return 对我来说是一个 500 错误,没有任何消息。

我在尝试 return 嵌套对象时需要帮助。

athlete 周围缺少一对方括号。这可能是导致此错误的原因。

Activity.fetch({withRelated: ['athlete']}).then(...)

编辑

嘿@Derekedelaney,我尝试实施同一个项目,但没有遇到任何问题。你可以找到它here。我得到了这样的输出

[
  { id: 1,
    athlete_id: 1,
    type: 'run',
    distance: '5',
    athlete: { id: 1, firstname: 'john', lastname: 'doe' } 
  },
  { id: 2,
    athlete_id: 2,
    type: 'walk',
    distance: '7',
    athlete: { id: 2, firstname: 'jane', lastname: 'doe' }
  } 
]

请注意,我使用的是 Bookshelf registry 插件,所以请看一遍。如果您有任何困难,请告诉我。

您的表使用非标准主键,因此您必须使用 idAttribute 属性 指定它们。只需将您的模型更改为:

const Athlete = bookshelf.Model.extend({
    tableName: 'athlete',
    idAttribute: 'athlete_id'
    activities: function() {
        return this.hasMany('Activity', 'athlete_id');
    }
});

const Activity = bookshelf.Model.extend({
    tableName: 'activity',
    idAttribute: 'activity_id'
    athlete: function() {
        return this.belongsTo('Athlete');
    }
});

仅获取普通的 500 HTTP 状态也无济于事。我建议您在 fetch() 代码中添加一个 catch 子句,例如:

Activity
  .fetch({withRelated: ['athlete']})
  .then(...)
  .catch(ex => {
     log.err('Error while fetching', ex); // or at least 'console.dir(ex)'
     throw ex;
  })