Loopback 4 @hasOne relation

343 Views Asked by At

I have a question about Loopback 4 and @hasOne relation. I have read the documentation, but I didn´t find it.

User model:

@model({ settings: {} })
export class User extends Entity {
  @property({
    type: 'string',
    id: true,
    required: true,
  })
  id: string;


  @hasOne(() => Settings)
  settings: Settings;


  constructor(data?: Partial<UserSettings>) {
    super(data);
  }

}

Model Settings

@model({ settings: {} })
export class Settings extends Entity {
  @property({
    type: 'string',
    id: true,
    required: true,
  })
  id: string;


 @property({
  type: 'string',
 })
 userId: string;
    
 constructor(data?: Partial<UserSettings>) {
  super(data);
 }

}

QUESTION: To make the @hasOne relation work I have to add the field: userId (the name of the other class in lowercase with id at the end). Is there a way to use a field called in another way? how can I indicate that the relation is with the field id? why I have to use yes or yes a field called nameoftheothermodel + Id?

Thanks in advance

Best

1

There are 1 best solutions below

0
Rifa Achrinza On BEST ANSWER

LoopBack 4 relation decorators accept an additional argument for relation metadata:

User Model

@model({ settings: {} })
export class User extends Entity {
  @property({
    type: 'string',
    id: true,
    required: true,
  })
  id: string;


  @hasOne(() => Settings, {
    keyTo: 'myCustomForeignKey' // Add this
  })
  settings: Settings;


  constructor(data?: Partial<UserSettings>) {
    super(data);
  }
}

Settings Model

@model({ settings: {} })
export class Settings extends Entity {
  @property({
    type: 'string',
    id: true,
    required: true,
  })
  id: string;


 @property({
  type: 'string',
 })
 myCustomForeignKey: string; // Custom 'foreign key'
    
 constructor(data?: Partial<UserSettings>) {
  super(data);
 }
}