Abhishek Tyagi
Abhishek Tyagi

Reputation: 142

How to query related objects in Loopback 4

I have two models Post and User.

I've marked userId property of post with belongsTo decorator

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

but when I use include filter on post.

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

Loopback throws an error

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)

Upvotes: 1

Views: 690

Answers (2)

Tan Nguyen
Tan Nguyen

Reputation: 1091

First of all, create relation by command:

lb4 relation

after that:

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

You can refer here : https://strongloop.com/strongblog/inclusion-of-related-models/

Upvotes: 1

Krosan
Krosan

Reputation: 734

As far as i know inclusion of related Models is currently not implemented. see the Inclusion Issue and lack of features compared to previous version

Upvotes: 2

Related Questions