Search code examples
databasetypeorm

TypeOrm how to model and relation "Reference" tables


I know this probably is a very nooby question but I have not found a way to do this that "feels right".

I learned that if you have a field in an entity that has a finite set of possible values you define what's called a "reference" or a "dictionary" or a "Enum table" with the possible values to ensure integrity and save space

For example if an User has a BloodType that can be only "A", "B", "AB" or "O", instead of having a VARCHAR BloodType column, we create a table called BloodTypes and then we have a BloodTypeId in the Users table.

So then, how do I model this properly in TypeOrm? This feels like a "User Bloodtype" relationship to me, but TypeOrm does not have that, it has "OneToOne" This is clearly not a OneToOne relationship because tho an user has only one BloodType, a BloodType can belong to many users. But manyToOne does not seem right either. I dont feel natural to see a column like the following on my User entity

@ManyToOne(type => BloodType, bloodType => bloodType.users)
bloodType: BloodType;

Also it requires me to add a oneToMany relationship in my BloodType entity. Is this really the right way to do this? or am I missing something? This clearly works but somehow does not "feel right"

Also, if I want to receive an user like the following

obUser = {
    bloodType: {name: "AB"}
}

and save it, how do I tell TypeOrm from User.create(obUser) to assing the current existing bloodtype instead of creating a new one into the database?

I hope this is not "opinion based" as I am looking for the proper way to do this as my current method does work.

I hope I am not drowning myself in a glass of water.

Thanks a lot for any guidance!


Solution

  • I know this was posted this a while ago, I had the same issue so will share how I resolved it so that others can find this in future as well.

    In the example below I have a Customers table which has a status field that joins the data dictionary / reference table. The data dictionary / reference entity definition does not have a reciprocating property, luckily that is not required.

    Here is the column definition in the Customers table:

    @ManyToOne(() => DataDictionaryEntry)
    @JoinColumn([{ name: 'status_id', referencedColumnName: 'id' }])
    status: DataDictionaryEntry
    

    This creates a column in the Customers table called status_id, which is the id of the linked data dictionary / reference record.