SoftwareBrothers / adminjs-mikroorm

MIT License
3 stars 6 forks source link

1:1 relation with "eager: true" not showing up as reference #17

Open mbise1993 opened 1 year ago

mbise1993 commented 1 year ago

Description I have a couple of entities defined which have a 1:1 relation:

@Entity()
export class User extends BaseEntity<User, 'id'> {
  @PrimaryKey()
  id!: number;

  @Property()
  @Index()
  name!: string;

  @OneToOne(() => NotificationPreferences, (preferences) => preferences.user, {
    ref: true,
    eager: true,
    orphanRemoval: true,
  })
  notificationPreferences!: Ref<NotificationPreferences>;
}

@Entity()
export class NotificationPreferences extends BaseEntity<
  NotificationPreferences,
  'id'
> {
  @PrimaryKey()
  id!: number;

  @Property()
  frequency!: string;

  @OneToOne(() => User, (user) => user.notificationPreferences, {
    ref: true,
    owner: true,
  })
  user!: Ref<User>;
}

When I navigate to the "User" resource in AdminJS and select a user, the "Notification Preferences" field is blank. However, if I navigate to the "Notification Preferences" resource, I can see the linked user. After some experimenting, I've found that I can get it to work by removing the eager: true option from the notificationPreferences reference on the User entity.

Installed libraries "@adminjs/express": "^5.0.1", "@adminjs/mikroorm": "^2.0.0", "@adminjs/nestjs": "^5.1.0", "@mikro-orm/core": "^5.6.0", "@mikro-orm/nestjs": "^5.1.2", "@mikro-orm/postgresql": "^5.6.0",

Additional details Here is the JSON response from the request to /admin/api/resources/User/records/1/show with the eager: true option set:

{
  "params": {
    "id": 1,
    "name": "Admin Use",
    "notificationPreferences.id": 1,
    "notificationPreferences.frequency": "every",
    "notificationPreferences.lastEmailDate": null,
    "notificationPreferences.user": 1
  },
  "populated": {
    "musician": { ...data }
  },
  "baseError": null,
  "errors": {},
  "id": 1,
  "title": "Admin Use",
  "recordActions": [ ...data ],
  "bulkActions": []
}

And without the eager: true option set (this works):

{
  "params": {
    "id": 1,
    "name": "Admin Use",
    "notificationPreferences": 1
  },
  "populated": {
    "notificationPreferences": { ...data },
    "musician": { ...data }
  },
  "baseError": null,
  "errors": {},
  "id": 1,
  "title": "Admin Use",
  "recordActions": [ ...data ],
  "bulkActions": []
}
dziraf commented 1 year ago

This might work if you define a @Property for notificationPreferencesId

mbise1993 commented 1 year ago

My relation is going the other way actually, there's a userId column on NotificationPreferences, but no notificationPreferencesId column on User. I did try defining a @Property for userId, but no luck