1
votes

I don't know if I'm just blind or something but how can I do the following:

I have a User model with a hasOne relation to a UserData model. I only want one property of UserData directly in the results of User.

The relation in User looks like this:

"relations": {
  "userData": {
    "type": "hasOne",
    "model": "UserData"
  }
}

And the default scope in User:

"scope": {
  "include": "userData"
}

So the result for one User is:

[
  {
    "id": 5,
    "email": "[email protected]",
    "name": "Example",
    "userData": {
      "id": 5,
      "birthdate": "1971-09-06T00:00:00.000Z"
    }
  }
]

But what I want is this:

[
  {
    "id": 5,
    "email": "[email protected]",
    "name": "Example",
    "birthdate": "1971-09-06T00:00:00.000Z"
  }
]

How can I achive this?

Edit:

The two model definitions:

ChiliUser:

{
  "name": "ChiliUser",
  "base": "ChiliUserData",
  "idInjection": true,
  "options": {
    "validateUpsert": true,
    "mysql": {
      "table": "person"
    }
  },
  "properties": {
    "id": {
      "type": "number"
    },
    "email": {
      "type": "string"
    },
    "password": {
      "type": "string"
    },
    "vorname": {
      "type": "string"
    },
    "name": {
      "type": "string"
    },
    "spitzname": {
      "type": "string"
    },
    "strasse": {
      "type": "string"
    },
    "plz": {
      "type": "number"
    },
    "ort": {
      "type": "string"
    },
    "geolat": {
      "type": "string"
    },
    "geolng": {
      "type": "string"
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": []
}

ChiliUserData:

{
  "name": "ChiliUserData",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true,
    "mysql": {
      "table": "person_data"
    }
  },
  "properties": {
    "id": {
      "type": "number"
    },
    "person_id": {
      "type": "number"
    },
    "birthdate": {
      "type": "date"
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": []
}
1

1 Answers

1
votes

Are you using the built-in User model? If you are, you can simply extend it with your UserData model using base: "User", and the underlying schema will be as you desire:

{
  "name": "UserData",
  "base": "User",
  "properties": {}
  ...
}

But this setup would mean you'd use UserData over User in your code. Since the built-in User model gets in the way, I'd recommend a different word like Person or Customer, in which case it would look like:

{
  "name": "Person",
  "base": "User",
  "properties": {
    ...extra user data properties only...
  }
  ...
}

This way, only Person will have all the extra "user data" fields on it, but will also include all the fields/methods defined for User inside node_modules/loopback/common/models/User.json. If you're using MySQL, the Person table will be created with the combination of fields from both User and Person.