Skip to content

CLI generator ignores keyTo option when creating belongsTo relations #11647

Description

@Abubakar-K-Back

Describe the bug

When using lb4 relation to generate a belongsTo relation with a custom keyTo (targeting a non-primary-key field on the destination model), the CLI generator does not include keyTo in the generated @belongsTo decorator. Additionally, the foreign key type is always resolved from the destination model's primary key type instead of the actual keyTo field type.
This means the generated code is silently broken the relation resolves against the wrong field at runtime.

Note: The keyTo option is fully supported in @loopback/repository at runtime. The bug is only in the CLI generator not passing it through to the generated code.

Steps to reproduce:

  1. Have two models where the target model has a non-PK unique field:

    • Source model: KundeThrough
    • Target model: Kunde with a unique field bexioId: string (not the PK)
  2. Run: lb4 relation

    • Relation type: belongsTo
    • Source model: KundeThrough
    • Target model: Kunde
    • Foreign key name: contactId
    • Custom keyTo: bexioId
  3. Inspect the generated property in kunde-through.model.ts

Expected behavior:
@belongsTo(() => Kunde, {name: 'contact', keyTo: 'bexioId'})
contactId: string; // type resolved from bexioId (string), not PK (number)

Actual behavior:
@belongsTo(() => Kunde, {name: 'contact'})
contactId: number; // keyTo missing, FK type wrong (uses PK type instead)

Logs

Additional information

No response

Reproduction

n/a

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions