简体   繁体   English

BookshelfJS关系 - hasMany

[英]BookshelfJS Relationship - hasMany

I'm using BookshelfJS as my ORM. 我正在使用BookshelfJS作为我的ORM。 I have 3 models. 我有3个型号。

TripHistory
user_id
route_id

Route
id
name

Users
id
name

From my user model, I have a relationship 从我的用户模型,我有一个关系

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

And the TripHistory has a relationship like 和TripHistory有一种关系

route() {
  return this.belongsTo(Route)
}

The problem here is, when I try to get the trip History, I want to get just the route name. 这里的问题是,当我尝试获取历史记录时,我想得到路线名称。 Running 运行

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

But I really will love only the route object 但我真的只会喜欢路线对象

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

        },

Any idea how I can fix this from the model? 知道如何从模型中解决这个问题吗?

Thank you. 谢谢。

I solved my own problem. 我解决了自己的问题。 Here is the right solution 这是正确的解决方案

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

I hope this helps someone out there. 我希望这可以帮助那里的人。

you can add a function to the TripHistory model with definition like below... 您可以向TripHistory模型添加一个函数,其定义如下...

fetchWithOnlyRouteRelationship: async function() {

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

then refer to it in your service / controller like so.. 然后在你的服务/控制器中引用它,就像这样..

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM