Unable to define polymorphic relations, Could not find "relation" relation for Model
I am facing an issue with polymorphic relations.
{
"name": "Organisation",
...
"relations": {
...
"behalfWriteAuthorizations": {
"type": "hasMany",
"model": "WriteAuthorization",
"polymorphic": {
"as": "authority",
"foreignKey": "authorityId",
"discriminator": "authorityType"
}
}
...
This code raises an error saying
Could not find "behalfWriteAuthorizations" relation for Organisation
While the same code in another model "Writer", it just works fine
{
"name": "Writer",
...
"relations": {
...
"behalfWriteAuthorizations": {
"type": "hasMany",
"model": "WriteAuthorization",
"polymorphic": {
"as": "authority",
"foreignKey": "authorityId",
"discriminator": "authorityType"
}
}
...
hey @sahilanguralla I am trying to reproduce your problem, for a better debug, could you fork this sandbox and replace it with your code? Thanks!
Here is the bug reproduced. https://github.com/sahilanguralla/loopback-sandbox
hey @sahilanguralla it's quite a weird problem but I think I find out where the problem comes from:
To simplify the issue I change db to default and delete properties in model to just test the relation, you got error due to the sequence of models stored in server/model-config.json:
https://github.com/sahilanguralla/loopback-sandbox/blob/master/server/model-config.json#L43
The error only happens when we define a polymorphic hasMany relation
"relations": {
"myrelation": {
"type": "hasMany",
"model": "modelB",
"polymorphic": "mypolymorphic"
}
},
in common/modelA.json
And modelA is stored after modelB in server/model-config.json
- The sequence doesn't affect hasMany
- ModelB could not exist but cannot stored before ModelA
So as a workaround, I suggest you manually move Organisation onto top of WriteAuthorization, then your code should work. We will dig into the reason then.
Please let me know if the workaround also works for you :) thanks!
Ya, it works. Actually, I already figured out same. The main concern about reporting the issue was that doesn't sound to be a good thing as far I know about loopback. As it happens in hasMany relations case, sequence of models in model-config.json shouldn't raise any such error for a polymorphic relation too.
I found this occurring with hasOne polymorphic relations also. Seems to be resolved also by naming the relationship the same as the entity being referenced - but using plural if it is hasMany, and using singular if it is a hasOne relationship.
@beaglez thanks for providing us more details!