【问题标题】:Access related models inside the Loopback isomorphic client访问 Loopback 同构客户端中的相关模型
【发布时间】:2017-08-05 17:24:53
【问题描述】:

我想使用 Loopback 同构客户端获取给定公司的资料。

Company 模型使用 MySQL 连接器,并且配置文件位于 ElasticSearch 实例中。

环回客户端在我的前端应用程序中运行良好,以下代码运行成功:

let lbclient = window.require('lbclient')

lbclient.models.RemoteProfile.find().done(profiles => {
  // do something with the profiles array
})

我的目标是将配置文件作为嵌套资源获取:

/api/companies/{id}/profiles/

问题是:为什么下面的代码在客户端不起作用?

// This is the code I execute on the client
lbclient.models.RemoteCompany.findById(8, (err, company) => {
  company.profiles // undefined
})

// This code works very well on the server
Company.findById(8, (err, company) => {
   company.profiles((err, profiles) => {
     // profiles belong the the company having id=8
   }
})

common/models/company.json

{
  "name": "Company",
  "plural": "companies",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true,
      "default": "My Company"
    }
  },
  "validations": [],
  "relations": {
    "profiles": {
      "type": "hasMany",
      "model": "Profile",
      "foreignKey": "company_id"
    }
  },
  "acls": [],
  "methods": {}
}

common/models/profile.json

{
  "name": "Profile",
  "plural": "profiles",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string"
    }, 
  },
  "validations": [],
  "relations": {
    "company": {
      "type": "belongsTo",
      "model": "Company",
      "foreignKey": "company_id"
    }
  },
  "acls": [],
  "methods": {}
}

client/loopback/models/remote-company.json

{
  "name": "RemoteCompany",
  "base": "Company",
  "plural": "companies",
  "trackChanges": false,
  "enableRemoteReplication": true
}

client/loopback/models/remote-profile.json

{
  "name": "RemoteProfile",
  "base": "Profile",
  "plural": "profiles",
  "trackChanges": false,
  "enableRemoteReplication": true
}

【问题讨论】:

    标签: javascript loopbackjs isomorphic-javascript


    【解决方案1】:

    您需要像这样在查询中包含个人资料:

    lbclient.models.RemoteCompany.findById(8, {include: 'profiles'}, (err, company) => {
    
    })
    

    【讨论】:

    • 感谢您的回答,这是我想出的第一个解决方案,但不幸的是,我无法以这种方式执行“计数”。
    • @AntonioTrapani count 关于什么?
    • 计算公司拥有的配置文件并受过滤器约束。一个典型的用例是分页。
    • @AntonioTrapani 啊哈。您可以使用find 方法进行分页,count 用于统计公司拥有的个人资料
    • 当然,我可以在服务器上做到这一点,但显然,没有办法在客户端上做到这一点,因为当我得到公司时,对象没有方法company.profiles
    猜你喜欢
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多