Celestine Omin
Celestine Omin

Reputation: 41

BookshelfJS Relationship - hasMany

I'm using BookshelfJS as my ORM. I have 3 models.

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

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.

Upvotes: 1

Views: 363

Answers (2)

Celestine Omin
Celestine Omin

Reputation: 41

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.

Upvotes: 3

Edwin O.
Edwin O.

Reputation: 5276

you can add a function to the TripHistory model with definition like below...

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();

Upvotes: 0

Related Questions