BookshelfJS 关系 - hasMany

BookshelfJS Relationship - hasMany

我正在使用 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']

returns

"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"

        },

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

谢谢。

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

fetchWithOnlyRouteRelationship: async function() {

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

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

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

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

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

我希望这对那里的人有所帮助。