BookshelfJS关系 - hasMany

时间:2017-08-19 01:18:55

标签: node.js orm bookshelf.js

我使用BookshelfJS作为我的ORM。我有3个型号。

TripHistory
user_id
route_id

Route
id
name

Users
id
name

从我的用户模型中,我有一段感情

trips() {
  return this.hasMay(TripHistory)
}

TripHistory有一个像

这样的关系
route() {
  return this.belongsTo(Route)
}

问题在于,当我尝试获取历史记录时,我想获得路线名称。正在运行

 withRelated: ['trips.route']

返回

"trips": [
        {
            "id": 1,
            "user_id": 1,
            "route_id": 1,
            "driver_id": 1,
            "trip_id": 1,
            "created_at": "2017-08-09T16:46:34.000Z",
            "updated_at": "2017-08-09T16:46:34.000Z",
            "route": {
                "id": 1,
                "pickup": "Fadeyi",
                "destination": "Jibowu",
                "departure_time": "6:00",
                "time_of_day": "AM",
                "day_of_week": "MON",
                "fair": 500,
                "created_at": "2017-08-09T16:21:58.000Z",
                "updated_at": "2017-08-09T16:21:58.000Z",
                "pickup_coordinate": "6.528482899999999, 3.3628242",
                "destination_coordinate": "6.5177977, 3.3678641"
            }
        },

但我真的只会喜欢路线对象

"trips": [
        {

                "id": 1,
                "pickup": "Fadeyi",
                "destination": "Jibowu",
                "departure_time": "6:00",
                "time_of_day": "AM",
                "day_of_week": "MON",
                "fair": 500,
                "created_at": "2017-08-09T16:21:58.000Z",
                "updated_at": "2017-08-09T16:21:58.000Z",
                "pickup_coordinate": "6.528482899999999, 3.3628242",
                "destination_coordinate": "6.5177977, 3.3678641"

        },

我知道如何从模型中解决这个问题吗?

谢谢。

2 个答案:

答案 0 :(得分:3)

我解决了自己的问题。这是正确的解决方案

trips() {
  return this.hasMany('Route')
    .through('TripHistory', 'id', 'user_id', 'route_id');
}

我希望这可以帮助那些人。

答案 1 :(得分:0)

您可以向TripHistory模型添加一个函数,其定义如下...

fetchWithOnlyRouteRelationship: async function() {

        const result = await this.fetchAll( withRelated: ['trips.route'] );
        return result['route'];
},

然后在你的服务/控制器中引用它,就像这样..

new TripHistory({id : bar }).fetchWithOnlyRouteRelationship();