I have the following doubt that I couldn't find clearly in objection.js docs. I have the following 2 Models:
export class Language extends BaseId {
name: string;
static tableName = 'Languages';
static jsonSchema = {
type: 'object',
required: ['name'],
properties: {
name: { type: 'string', minLength: 1, maxLength: 80 }
}
};
}
export class Country extends BaseId {
name: string;
languages: Language[];
static tableName = 'Countries';
static jsonSchema = {
type: 'object',
required: ['name'],
properties: {
name: { type: 'string', minLength: 1, maxLength: 120 }
}
};
static relationMappings: RelationMappings = {
languages: {
relation: Model.ManyToManyRelation,
modelClass: Language,
join: {
from: 'Countries.id',
through: {
from: 'CountriesLanguages.country_id',
to: 'CountriesLanguages.language_id',
extra: ['oficial']
},
to: 'Languages.id'
}
}
};
}
I want to insert a new country like:
{
name: "Country Name",
languages: [
{ id: 1, official: true },
{ id: 2, official: true },
{ id: 3, official: false }
]
}
As you can see, I don't want to create a new Language, I want to just add the reference with the extra property. I just want to create the country with the relations. What's the correct way for inserting like that? I couldn't find the docs, just found a way where it creates Languages as well.
Thanks!
I asked the project maintainer about it so I'll answer my own question with his answer in case someone else is interested:
Country
.query()
.insertGraph({
name: 'Finland',
languages: [{
// This is the id of the language. You can change "#dbRef" into
// some other property by overriding `Model.dbRefProp` but you
// cannot use the model's id column name.
"#dbRef": 1,
oficial: true
}, {
"#dbRef": 2,
oficial: false
}]
})