本文介绍了回送-包含关系的计算属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个回送应用程序,我希望能够在API调用中包含通过关系计算出的属性.例如,假设我有一个apartment模型和一个address模型. address具有属性citystate.

I have a loopback app and I'd like to be able to include computed properties from relations in an API call. For example, say I have an apartment model and an address model. The address has properties city and state.

我想打个电话到公寓模型,并从相关的address模型中将城市和州作为一个字符串包含进来.

I'd like to make one call, to the apartment model, and include the city and state as a single string from the related address model.

我从@Raymond Feng对此问题的回答中获得了一些启发,并尝试了以下方法(请使用coffeescript/伪代码):

I took some inspiration from @Raymond Feng's answer to this question, and tried the following approach (excuse the coffeescript/pseudo-code):

address.defineProperty(address.prototype, "fullAddress",
    get: () -> return address.city + " " + address.state
)

但是,当我尝试时:

apartment.findOne({
    include:
        relation: "address"
        scope:
            fields:
                fullAddress: true
}, (err, apartment) ->
    console.log(apartment)
)

我知道

Error: ER_BAD_FIELD_ERROR: Unknown column 'fullAddress' in 'field list'

值得注意的是,当我尝试在不指定字段的情况下查询地址模型时,会得到一个名为'[object Object]'的属性,其值为null,我怀疑这是我尝试定义fullAddress属性的结果

Notably, when I try to query the address model without specifying fields, I get an attribute named '[object Object]' with a value of null, which I suspect is a result of my attempt to define the fullAddress property.

我认为我正在使用错误的语法来解决问题.我正在寻找的可能吗?如果可以,该怎么办?

I assume that I'm approaching the problem with the wrong syntax. Is what I am looking for possible, and if so, how do I do it?

推荐答案

环回不支持计算出的属性,这是不对的了(不再).

It is not true (anymore) that Loopback doesn't support calculated properties.

这可以通过Loopback的操作钩子完成,正如我在此处所述:环回模型中的动态属性或聚合函数

This can be done with Loopback's operational hooks as I described here: Dynamic Properties or Aggregate Functions in Loopback Models

这篇关于回送-包含关系的计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 08:38