我使用书架和knex连接到PostgreSQL数据库。我试图检索有一对多关系的数据。我的数据库如下:
表:运动员

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

表:活动
|------------------------------------|
|  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(...)
这又回来了
[
  {
    "id": "0",
    "athlete_id": "1",
    "type": "run",
    "distance": "5",
  },
  {
    "id": "1",
    "athlete_id": "0",
    "type": "walk",
    "distance": "7",
  }
]

我想要它回来的是
[
  {
    "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(...)但这会为我返回一个500错误,没有任何消息。
我需要帮助尝试返回嵌套对象。

最佳答案

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

请注意,我正在使用书架注册表插件,所以请通过一次。如果你有什么困难请告诉我。

09-26 19:46