BookshelfJS关系 – 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) }
这里的问题是,当我尝试获取行程历史logging时,我只想得到路线名称。 运行
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" },
任何想法如何我可以解决这个从模型?
谢谢。
我解决了我自己的问题。 这是正确的解决scheme
trips() { return this.hasMany('Route') .through('TripHistory', 'id', 'user_id', 'route_id'); }
我希望这可以帮助那里的人。
你可以添加一个functionTripHistory
模型像下面的定义…
fetchWithOnlyRouteRelationship: async function() { const result = await this.fetchAll( withRelated: ['trips.route'] ); return result['route']; },
然后在你的服务/控制器中像这样引用它。
new TripHistory({id : bar }).fetchWithOnlyRouteRelationship();