在 ember 中的属于关系中查找数据

Finding data in a belongs to relationship in ember

我正在尝试在 ember 项目中查找与当前用户关联的帐户。我能够获取用户 ID 并通过 {{account.user.id}} 将其传递给 handlebars 脚本。然而,我在我的模型挂钩中尝试使用此用户 ID 查找帐户的所有尝试都没有成功。

我当前的模型挂钩 routes/my-account.js:

model (params) {
    let accountID = this.store.query('account', { filter: { user: { id:currentUser} } });
    console.log(accountID.id);
    return this.get('store').findRecord('account', accountID);
  }

accountID 作为 ember class 返回,但我似乎无法从中解析任何数据。我将如何从返回的 ember class 中获取 ID 以便将其传递给我的获取请求?

要从 Ember 对象获取和设置属性,您必须使用 getset,例如:

console.log(account.get('id'));

不过,更重要的是,您的 .query 将(或至少应该)return 一组与过滤器匹配的 account 模型。它将被包裹在一个承诺中——因为它是一个异步网络调用——所以你需要 .then 它。您可能只想获取第一个帐户:

model() {
  return this.store.query('account', { filter: { user: { id: currentUser } } })
    .then(function(accounts) {
      return accounts.get('firstObject');
    });
}

如果你有一个合适的 {json:api},你可以得到 user,然后从例如/api/users/:id/account。您的模型挂钩看起来像:

model() {
  return this.store.findRecord('user', currentUser)
    .then(function(user) {
      return user.get('account');
    });
}