简体   繁体   中英

Loopback 4 - Is it possible to define id property's length?

Using LB4 + MySQL DB through loopback-connector-mysql to create tables on DB.

A {id: string, name: string}

id names
0007bc40-814b-11ec-8128-4df48bd1ae4d John
0007bc40-814b-11ec-8128-4df48bd1ae3d Marie

B {id: string, aId:string, name: string}

id aId names
0007bc40-814b-11ec-8128-4df48bd1ae2d 0007bc40-814b-11ec-8128-4df48bd1ae4d Eve
0007bc40-814b-11ec-8128-4df48bd1ae1d 0007bc40-814b-11ec-8128-4df48bd1ae4d Ronald
0007bc40-814b-11ec-8128-4df48bd1ae0d 0007bc40-814b-11ec-8128-4df48bd1ae3d Philipe

To create those models, I've used this code:

A

export class Payroll extends Entity {
    @property({
        type: 'string',
        id: true,
        defaultFn: 'uuid',
    })
    id: string;

    
    @property({
        type: 'string',
        required: true,
        length: 64,
    })
    name: string;
}

B

export class Payroll extends Entity {
    @property({
        type: 'string',
        id: true,
        defaultFn: 'uuid',
    })
    id: string;


    @belongsTo(() => A)
    aId: string;
    
    @property({
        type: 'string',
        required: true,
        length: 64,
    })
    name: string;
}

On both tables, id is a VARCHAR(255), although it only needs a VARCHAR(36) On B table, aId is a VARCHAR(512), which is even worse... This could be solved by defining aId as follows:

@belongsTo(() => A, undefined, { length: 36, }) aId: string;

Now, b.aId is a VARCHAR(36), but then i get the error following error:

Error: UNKNOWN_CODE_PLEASE_REPORT: Referencing column 'aId' and referenced column 'id' in foreign key constraint 'fk_a_b_aId' are incompatible", because both VARCHAR have different size.

How can I tell LB4 which length (in this example, 36)of the ID property I want on DB?

Thank you

this works for me.. I prefer to use fixed char guid - old habits;)

//// For ID (Primary key)
@property({
  type: 'string',
  id: true,
  defaultFn: 'uuidv4',
  dataType: 'char',
  limit: 36,
})
id?: string;

//// for relations
@belongsTo(
  () => RelatedModel,
  {},   // Relation Meta
  {     // Property Meta
    dataType: 'char',
    limit: 36
  }
)
ForeignKeyId: string;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM