question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

@OneToMany w/ cascade: am I just setting this up wrong?

See original GitHub issue

Issue type:

[x] question [ ] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [x] postgres [ ] sqlite [ ] sqljs [ ] react-native

TypeORM version:

[ ] latest [x] @next [ ] 0.x.x (or put your version here)

I’m trying to set up @OneToMany relationships with cascade. The child objects get inserted into the database, but the foreign key value (gather_id) is null. I’ve been struggling to figure out whether I have this set up correctly.

// Parent class
@Entity('gathers')
export class Gather {

    constructor(data?: GatherDataType) {
        if (data) {
            this.appVersion = data.appVersion;
            this.createPacketObjectsFromRawHex(data.rawData);
        }
    }

    @PrimaryGeneratedColumn()
    id: number;

    @Column({
        name: 'app_version',
    })
    appVersion: string;

    @OneToMany(type => Device, device => device.id, {
        cascade: true,
        onDelete: 'CASCADE',
    })
    devices: Device[];

    createPacketObjectsFromRawHex = (rawData: RawDataType) => {

        const packetObjects = {};

        Object.entries(rawData).forEach(d => {
            const syncTime = +d[0];
            const rawHex = d[1];
            const typeHex = rawHex.substr(8, 4);
            let packetObj = {};

            switch (typeHex) {
                // simplified... removed most cases
                case PacketType.Device:
                    packetObj = new Device(rawHex, syncTime);
                    break;
            }

            if (!packetObjects[typeHex]) {
                packetObjects[typeHex] = [];
            }

            packetObjects[typeHex].push(packetObj);
        });

        this.devices = packetObjects[PacketType.Device];
    }
}

// Child class
@Entity('devices')
export class Device extends BatteryDeviceBase {

    constructor(rawHex?: string, syncTime?: number) {
        super(rawHex, syncTime);
    }

    @ManyToOne(type => Gather, gather => gather.devices)
    @JoinColumn({ name: 'gather_id' })
    gather: Gather;

}

// How I'm calling this, passing in a `gatherData` JSON object...
const gather = new Gather(gatherData);
await connection.manager.save(gather);

All the inserts happen, i.e., a gather row and device rows, but device.gather_id is null.

I tried setting nullable: false on the @ManyToOne column but that just results in an INSERT error, as one would expect.

I tried cascade: true on the @ManyToOne but that resulted in no inserts at all.

I also tried calling the createPacketObjectsFromRawHex method after creating the Gather object (i.e., not in the constructor), but that didn’t make a difference.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:2
  • Comments:10 (3 by maintainers)

github_iconTop GitHub Comments

6reactions
vedranjukiccommented, Feb 3, 2020

I’m facing the same issue

1reaction
CemYil03commented, Nov 10, 2022

Let’s use an example for a one to many relation: one User has many Posts. In the User class you would find: @OneToMany(() => Post, (post: Post) => post.user, { cascade: true }). { cascade: true } gives the direction to resolve and persist nested relations when you use thesave method on repositories, nothing else.

usersRepository.save({
   ...userFields,
   posts: [        // <-- { cascade: true } triggers that this gets detected and resolved to sql insert statements
      { ...postFieldsForFirstPost },
      { ...postFieldsForSecondPost }
   ]
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

Hibernate Cascading problems with OneToMany
On your OneToMany side, i.e testParent , you need to have CascadeType. ALL or include CascadeType.
Read more >
Why you should avoid CascadeType.REMOVE for to-many ...
The CascadeTypes REMOVE and ALL create serious issues for to-many associations. Here is what you should do instead.
Read more >
Cascade - JPA & Hibernate annotation common mistake
Explanation. Look in the code, @OneToMany is from JPA , it expected a JPA cascade – javax. persistence. CascadeType.
Read more >
The best way to map a @OneToMany relationship with JPA ...
While adding a OneToMany relationship is very easy with JPA and ... Consider we have the following mapping: ... cascade = CascadeType.ALL,.
Read more >
Cascade Delete - EF Core | Microsoft Learn
Entity Framework Core (EF Core) represents relationships using foreign keys. An entity with a foreign key is the child or dependent entity in ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found