首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >回环:如何访问afterRemote中的关系

回环:如何访问afterRemote中的关系
EN

Stack Overflow用户
提问于 2018-08-06 10:23:18
回答 2查看 175关注 0票数 0

我为仓库模型设置了以下afterRemote方法:

代码语言:javascript
复制
  Depot.afterRemote('find', function(context, depots, next) {

        context.result.forEach(depot => {
          console.log(depot.drivers);
          depot.address = depot.street_name + ' ' + depot.door_number;
          depot.driver_count = depot.drivers.length;
        });

        next()
      })

在json响应中,depot.drivers包含正确的数据。

但是,当我试图在上面的方法中访问depot.drivers时,我得到了一些奇怪的输出:

代码语言:javascript
复制
{ [Function: f]
  _receiver: { postal_code: '1216BS',
     door_number: '3',
     street_name: 'Straat naam',
     city: 'Hilversum',
     lat: null,
     lng: null,
     created: 2018-04-03T01:49:12.000Z,
     id: 23,
     distributor_id: 2,
     distributor: { sys_id: 1,
        name: 'distributeur naam',
        contact_person: 'Persoon B',
        phone: '000-000000',
        email: 'info@d.nl',
        created: 2018-03-06T00:22:33.000Z,
        id: 2 },
     drivers: List [] },
  _scope: { where: { hub_id: 23 } },
  _targetClass: 'driver',
  find: [Function],
  getAsync: [Function],
  build: [Function: bound method],
  create: [Function: bound method],
  updateAll: [Function: updateAll],
  destroyAll: [Function: destroyAll],
  findById: [Function: bound method],
  findOne: [Function: findOne],
  count: [Function: count],
  destroy: [Function: bound method],
  updateById: [Function: bound method],
  exists: [Function: bound method] }

我最终希望添加一个depot.drivers_count属性,以便在前端表中显示连接到特定仓库的驱动程序的数量。

有人知道怎么做吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-06 11:45:24

看起来数据没有转换成JSON。

我想试试这个:

代码语言:javascript
复制
context.result.forEach(depot => {
      depot = depot.toJSON();
      console.log(depot.drivers);
      depot.address = depot.street_name + ' ' + depot.door_number;
      depot.driver_count = depot.drivers.length;
 });
票数 1
EN

Stack Overflow用户

发布于 2018-08-08 06:50:10

在回收站中,每个模型关系都可以使用回调函数访问,因为i/o是异步的。就像这样:

代码语言:javascript
复制
depot.drivers((err, drivers) => {
  // handle the error
  // do something with the drivers
})

还可以使用驱动程序模型操作挂钩跟踪数据更改并更新相关的Depot.drivers_count属性:

代码语言:javascript
复制
Driver.observe('after save', function(ctx, next) {
  // ctx.instance is the created or updated object
  if (ctx.isNewInstance) {
    // A new record was saved
    // Implementation depends on your models relationships
  } else {
    // A record was updated
    // Implementation depends on your models relationships
  }
  
  next()
})

Driver.observe('after delete', (ctx, next) => {
  // Implementation depends on your models relationships
  next()
})

更多信息,在这里回环操作钩-保存后

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51705461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档