I am using an existing MySQL database and its schemas, and am following the tutorial to build relations.
Due to the existing schema, Review has 'user_id' field that links to User's 'id.' I coded this relation in review.model.ts accordingly.
@belongsTo(() => User, {keyFrom: 'user_id', keyTo: 'id'})
user_id: number;
However, doing so gives me ...Cannot read property 'target' of undefined... error whenever ReviewRepository is called.
Modifying the code and its relevant parts like below does not cause any issues.
@belongsTo(() => User, {keyTo: 'id'})
userId: number;
How can I keep 'user_id' as a valid field for Review? Any help is appreciated.
Within ReviewRepository, instead of
this.user = this.createBelongsToAccessorFor('user', userRepositoryGetter);
I used
this.user = createBelongsToAccessor(
{
target: () => User,
name: 'user',
type: RelationType.belongsTo,
source: Review,
keyFrom: 'user_id',
keyTo: 'id',
},
userRepositoryGetter,
this,
);
This works for now, though not pretty. If anyone can provide an insight for making this code better, it'd be much appreciated!
+1 there is no clear documentation to build relations.
Please improve documentation
here https://loopback.io/doc/en/lb4/BelongsTo-relation.html you wrote
call the createBelongsToAccessorFor function in the constructor of the source repository class with the relation name (decorated relation property on the source model) and target repository instance and assign it the property mentioned above.
In code snippets source model decorated prorepty is customerId , but
this.customer = this.createBelongsToAccessorFor(
'customer', - I suppose it should be customerId
customerRepositoryGetter,
);
Ok, I managed documentation example to work. But I can't configure filter just to query just simple JOIN orders and its customers ((
@JuliaRakitina I believe you are referring to https://github.com/strongloop/loopback-next/issues/1352, which is a very important request IMO.
this.user = createBelongsToAccessor(Looks like the latest version of LB4 doesn't have createBelongsToAccessor()
For me, having this in review model
@belongsTo(() => User)
user_id: number;
and this in repository
this.user = this._createBelongsToAccessorFor(
'user_id',
userRepoGetter,
);
works. Is there anything different you are trying to achieve ?
Thank you all for chiming in. I've compiled the following criteria for this issue:
repository package to simulate the behaviour / cover the use case.
Most helpful comment
+1 there is no clear documentation to build relations.