【问题标题】:BookshelfJS Relationship - hasManyBookshelfJS 关系 - hasMany
【发布时间】:2017-08-19 01:18:55
【问题描述】:

我使用 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)
}

这里的问题是,当我尝试获取行程历史时,我只想获取路线名称。运行

 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"

        },

知道如何从模型中解决这个问题吗?

谢谢。

【问题讨论】:

    标签: node.js orm bookshelf.js


    【解决方案1】:

    我解决了自己的问题。这是正确的解决方案

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

    我希望这对那里的人有所帮助。

    【讨论】:

      【解决方案2】:

      您可以向TripHistory 模型添加一个函数,其定义如下...

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

      然后像这样在您的服务/控制器中引用它..

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

      【讨论】:

      • 是的,请TypeError: Cannot read property 'then' of undefined。您是否在项目或其他方面尝试过您的解决方案?
      猜你喜欢
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      • 2014-12-30
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多