@OneToMany w/ cascade: am I just setting this up wrong?
See original GitHub issueIssue 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:
- Created 5 years ago
- Reactions:2
- Comments:10 (3 by maintainers)
I’m facing the same issue
Let’s use an example for a one to many relation: one
User
has manyPosts
. 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.