2017-08-19 128 views
1

我正在使用BookshelfJS作爲我的ORM。我有3個模型。BookshelfJS Relationship - hasMany

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" 

     }, 

任何想法,我怎麼可以從模型解決這一問題?

謝謝。

回答

3

我解決了我自己的問題。這是正確的解決方案

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

我希望這可以幫助那裏的人。

0

你可以添加一個功能到TripHistory模型中包含的定義...

fetchWithOnlyRouteRelationship: async function() { 

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

則是指它在你的服務/控制器,像這樣..

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

不幸的是,這是行不通的。 –

+0

有沒有像任何錯誤? –

+0

是的,請'''TypeError:無法讀取undefined''屬性'then'。你是否在項目或其他方面嘗試瞭解決方案? –