How can I set the mysql table name for a model on loopback 4?
Asked Answered
S

2

9

I know that by default loopback 4 infers the name of the mysql database table from the model class or repository class. How can I set the table name to a custom string value? Probably I have to use a decorator, I have not been able to find anything in the documentation. Thanks.

Stertorous answered 15/10, 2018 at 18:59 Comment(1)
I have the same question.Homogeneous
G
18

In your decorator @model, just add the property name and it will work! For example:

@model({
  name: 'sales_order'
})
export class Order extends Entity{
...
}
Grangerize answered 26/10, 2018 at 18:13 Comment(1)
I don t remember exactly. Maybe the docs or most probably the typings definition or checked the code.Grangerize
F
2

In LB4 this is the cleanest approach for mapping a model to a DB table when their respective names differ. I found this LB4 issue stating that the LB3 "options" model syntax is not supported and provides an example similar to what I provided below: https://github.com/strongloop/loopback-next/issues/2134

For example let's say your Entity class is named Person and its data lives in DB table named Contacts. Specify the db table in the model definition using the LB4 model syntax -

@model({
  settings: {
    mysql: {
      schema: YOURSCHEMA,
      table: "Contacts"
    }
  }
})
export class Person extends Entity {...}

This snippet is from a working example that uses a MySql db.

Floridafloridia answered 18/1, 2019 at 3:57 Comment(1)
I did not need to declare the schema property. Just adding table resolved it. Though, the top level name property in the accepted answer also worked in loopback 4 (lb4).Intracranial

© 2022 - 2024 — McMap. All rights reserved.