Unable to delete subordinate relation entity when saving parent entity
See original GitHub issueIssue type:
[ ] question [x] bug report [ ] feature request [ ] documentation issue
Database system/driver:
[ ] cordova
[ ] mongodb
[ ] mssql
[x] mysql
/ mariadb
[ ] oracle
[ ] postgres
[ ] cockroachdb
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo
TypeORM version:
[x ] latest
[ ] @next
[ ] 0.x.x
(or put your version here)
Steps to reproduce or a small repository showing the problem:
My intention was to remove the subordinate entities in a relation from the parent entity.
For example, I’ve a Photo
entity which has a one-to-many relation setup with another entity MetaData
. So, when I retreive a Photo
entity with MetaData
relation, the Photo
entity should have a shape like this:
const photoEntity = this.photoRepository.findOne({where: {id: 5}, relations: ['metaData'])
photoEntity: {
file: 'someimage.jpg',
metaDatas: [
{
type: 'date',
data: '12-12-2000'
},
{
type: 'location',
data: '123.00 123.00'
}
]
}
Basically, the metaDatas
property in Photo
entity will be an array. My intention is to remove all MetaData
from the Photo
entity.
What I did was simply by setting the array of photoEntity.metaDatas
to an empty array and then save photoEntity
like so:
const photoEntity = this.photoRepository.findOne({where: {id: 5}, relations: ['metaData'])
// One photo can have many metadata rows of information in photoEntity.metaDatas
// Photo entity has a one-to-many relationship setup with MetaData entity
photoEntity.metaDatas = [] // Remove all metaDatas in photoEntity
this.photoRepository.save(photoEntity) // Throws error that ER_BAD_NULL_ERROR: Column 'photoId' cannot be null
However, this throws an error that Column 'photoId' cannot be null
. This is because instead of running a DELETE
query, the SQL TypeORM did an UPDATE
this:
sql: 'UPDATE `metaData` SET `photoId` = NULL, `updatedAt` = CURRENT_TIMESTAMP WHERE `metaDataId` = `123` }
Shouldn’t a DELETE
query be run instead of an update one?
In this case, how can I remove the MetaData
entities from the Photo
entity?
Issue Analytics
- State:
- Created 4 years ago
- Reactions:31
- Comments:20 (4 by maintainers)
Top GitHub Comments
I used orphanedRowAction and it worked for me.
Parent:
Child:
I think you’re looking for this: https://github.com/typeorm/typeorm/issues/1460