问题
I have used different models to simplify what I am trying to achieve and to remove clutter, although the theory should be the same as my actual project.
Use the following assumptions: A system can only have one type of speaker and one type of amp.
Say I have the following models:
*** System ***
- id
- name
- speakerId
- ampId
*** Speaker ***
- id
- name
*** Amp ***
- id
- name
I have added the following to my System.json model file (which i think is correct):
"relations": {
"speakers": {
"type": "hasOne",
"model": "Speaker",
"foreignKey": "speakerId"
},
"amps": {
"type": "hasOne",
"model": "Amp",
"foreignKey": "ampId"
}
},
When I start my app and open the API Explorer and go to create a new instance of Speaker or Amp it expects the following:
*** Speaker ***
- id
- name
- speakerId *** Why is this here??? ***
If I change the System.json model file to look like this (which I think is the wrong way to do it):
"relations": {
"speakers": {
"type": "hasOne",
"model": "Speaker",
"foreignKey": "id"
},
"amps": {
"type": "hasOne",
"model": "Amp",
"foreignKey": "id"
}
},
Everything looks right in the API explorer. So I add a few speakers and amps, then add a system.
When I add an include filter to the System GET request:
{"include":["speakers","amps"]}
It includes the speakers and amps but using the System.id as the index for the Speakers and Amps Models instead of System.speakerId and System.ampId. So to ellaborate if the:
System.id = 5
System.speakerId = 1
System.ampId = 3
It will include the speaker with an id of 5 and the amp with the id of 5 instead of including the speaker with an id of 1 and the Amp with an id of 3.
I want to be able to list all Systems including their related Speakers and Amps. How can this be done with Loopback. At the minute I am using the above models with in memory DB instead of my usual ones just to test. Any help would be appreciated as I am now at the point of tearing my hair out!
Regards, James
回答1:
Your relation between models is not correct. You need to tell loopbackjs to use hasMany through relation to get your data.
Your system.json should be changed to
"relations": {
"speaker": {
"type": "belongsTo",
"model": "Speaker",
"foreignKey": "speakerId"
},
"amp": {
"type": "belongsTo",
"model": "Amp",
"foreignKey": "ampId"
}},
And your speakers should be
"relations": {
"amps": {
"type": "hasMany",
"model": "Amp",
"foreignKey": "speakerId",
"through": "System"
},
amp.json
"relations": {
"speakers": {
"type": "hasMany",
"model": "Speaker",
"foreignKey": "ampId",
"through": "System"
},
来源:https://stackoverflow.com/questions/32252867/loopback-api-include-filters-not-working-as-expected