node.jsmodeladonis.jslucid

How can I automatically append a property from a relation to the root object?


How can I automatically append a property from a relation to the root object, as if it were a column from the same table but actually it is coming from another table.

Supose I have an User model that hasMany Emails.

How can I only append the email from the first Email of the User model, so that everytime I query the User model I get it like a property?

Example:

What I'm doing:

(await User.query().where('id', id).with('emails').first()).toJSON()
{
  "name": "Eleandro Duzentos",
  "emails": [
    { "email": "eleandro@inbox.ru" },
    { "email": "eleandro@mail.ru" }
  ]
}

What I want:

(await User.find(id)).toJSON()
{
  "name": "Eleandro Duzentos",
  "email": "eleandro@inbox.ru"
}

Obs: I'm not putting the email on the same table because, there's a chance that a user may need more then one email in a long future, but for now, it has only one.

How can I do that?


Solution

  • For the customized JSON response i would suggest the use of serializers. You can override the default serializers to get the desired result.

    You can refer to this - https://adonisjs.com/docs/4.0/serializers