如何在Loopback 4中查询相关对象

时间:2019-04-05 09:19:56

标签: node.js loopbackjs loopback v4l2loopback

我有两个模型Post和User。

我已使用belongsTo装饰器标记了post的userId属性

@belongsTo(() => User, {keyTo: 'id', name: 'user'})
userId: number;

但是当我在帖子上使用include过滤器时。

return await this.postRepository.find({
        "include": [{
            "relation": "user",
        }
        ]});

环回引发错误

Unhandled error in GET /posts: 500 Error: Relation "user" is not defined for Post model
at processIncludeItem (/node/posts/node_modules/loopback-datasource-juggler/lib/include.js:309:10)
at /node/posts/node_modules/loopback-datasource-juggler/lib/include.js:187:7
at /node/posts/node_modules/async/dist/async.js:3110:16
at eachOfArrayLike (/node/posts/node_modules/async/dist/async.js:1069:9)
at eachOf (/node/posts/node_modules/async/dist/async.js:1117:5)
at Object.eachLimit (/node/posts/node_modules/async/dist/async.js:3172:5)
at Function.Inclusion.include (/node/posts/node_modules/loopback-datasource-juggler/lib/include.js:185:9)
at /node/posts/node_modules/loopback-datasource-juggler/lib/connectors/memory.js:510:33
at process._tickCallback (internal/process/next_tick.js:61:11)

2 个答案:

答案 0 :(得分:1)

据我所知,目前尚未实现包含相关模型。 参见Inclusion Issuelack of features compared to previous version

答案 1 :(得分:1)

首先,通过命令创建关系:

lb4 relation

之后:

return this.postRepository.find(1, {include: [{relation: 'user'}]};)

您可以在这里参考:https://strongloop.com/strongblog/inclusion-of-related-models/