[Question] How to model parent-children/supertype-subtype relation in Objection.js?
Hey there folks! I've reached a point where I'm stuck with a problem and don't know where to go from here. I'll explain the problem with some info about the database modeling.
Hope someone has insights about this as I'm stuck on it for two days already. Appreciate it very much, thanks in advance. :)
The problem
I have a database model where both users and organizations can have multiple contact mechanisms. I've used exclusive polymorphic associations to model this (see contact_mechanisms table). The trick part is that contact mechanisms have three different subtypes (address, email and phone).
What I'm stuck at is when trying to move this modeling to Objection. For example in the OrganizationModel, I've tried to model it using the contact_mechanisms table as an association table and map the relation directly to the subtype. The problem is that when I try to create a new phone relation, the contact_mechanisms record is created after the phone one, so I don't have a contact_mechanism_id to associate with the phone record.
Not sure what I'm doing wrong here, and where to go. I didn't want to make another polymorphic association with all subtypes ids inside the contact_mechanisms table, but I'm not sure what would be the alternative.
The model
export class OrganizationModel extends Model {
static tableName = "organizations";
static relationMappings = {
phones: {
relation: Model.ManyToManyRelation,
modelClass: PhoneModel,
join: {
from: "organizations.id",
through: {
from: "contact_mechanisms.organization_id",
to: "contact_mechanisms.id",
},
to: "contact_mechanisms_phones.contact_mechanism_id",
},
},
};
name!: string;
phones?: PhoneModel[];
}
The database
