BookshelfJS Relationship - hasMany
问题描述:
我正在使用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"
},
任何想法,我怎么可以从模型解决这一问题?
谢谢。
答
我解决了我自己的问题。这是正确的解决方案
trips() {
return this.hasMany('Route')
.through('TripHistory', 'id', 'user_id', 'route_id');
}
我希望这可以帮助那里的人。
答
你可以添加一个功能到TripHistory
模型中包含的定义...
fetchWithOnlyRouteRelationship: async function() {
const result = await this.fetchAll(withRelated: ['trips.route']);
return result['route'];
},
则是指它在你的服务/控制器,像这样..
new TripHistory({id : bar }).fetchWithOnlyRouteRelationship();
不幸的是,这是行不通的。 –
有没有像任何错误? –
是的,请'''TypeError:无法读取undefined''属性'then'。你是否在项目或其他方面尝试了解决方案? –