1

I'm trying to set up a simple one-to-one relation between an item and item_name. The entity looks as follows:

@Entity('item')
export class ItemEntity {
  @PrimaryColumn('integer')
  id: number;

  @OneToOne(() => ItemNameEntity)
  @JoinColumn()
  name: ItemNameEntity;

  // ... other props
}

item-name.entity

@Entity('item_name')
export class ItemNameEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  en: string;

  @Column()
  fr: string;

  // ... other properties
}

I insert an item using the following payload:

{
      id: 26,
      name: { en: 'English name', fr: 'French name' },
}

It stores the item as expected, and adds a nameId column. The problem is that it does not insert anything into item_name, and thus the nameId column is null.

What am I missing here?

1 Answer 1

1

From this.

You have to set cascade: true on name relation in ItemEntity:

@Entity('item')
export class ItemEntity {
  @PrimaryColumn('integer')
  id: number;

  @OneToOne(() => ItemNameEntity, { cascade: true })
  @JoinColumn()
  name: ItemNameEntity;

  // ... other props
}

Setting cascade: true on ItemEntity tells TypeORM that if a new itemName is "linked" on an item and the item is saved, the new itemName should also be saved to the database.

Example:

const manager = getManager();
const item: ItemEntity = manager.create(ItemEntity, {
  id: 26,
  name: manager.create(ItemNameEntity, {
    en: 'English name',
    fr: 'French name'
  }),
});
await manager.save(ItemEntity, item);
Sign up to request clarification or add additional context in comments.

1 Comment

This pointed me in the direction I want to go in. I'm inserting the item_name entities before saving the parent (item), and it works. The itemId column is filled with the correct id. Thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.