如何使用书架js

时间:2017-06-24 19:01:04

标签: node.js postgresql one-to-many knex.js bookshelf.js

我正在使用bookshelf和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错误。

我需要帮助尝试返回嵌套对象。

2 个答案:

答案 0 :(得分:1)

您在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 注册表插件,所以请仔细阅读一次。如果您有任何困难,请告诉我。

答案 1 :(得分:1)

您的表使用非标准主键,因此您必须使用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;
  })