我有以下疑问,我无法在 objection.js 文档中清楚地找到。 我有以下两个模型:
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'
}
}
};
}
我想插入一个新的国家,例如:
{
name: "Country Name",
languages: [
{ id: 1, official: true },
{ id: 2, official: true },
{ id: 3, official: false }
]
}
如您所见,我不想创建新语言,我只想添加具有额外属性的引用。我只是想建立与国家的关系。 这样插入的正确方法是什么?我找不到文档,只是找到了一种创建语言的方法。
谢谢!
最佳答案
现在你应该可以简单地说:
Country.query()
.insertGraph({
name: "Country Name",
languages: [
{ id: 1, official: true },
{ id: 2, official: true },
{ id: 3, official: false }
]
}, {
// This tells `insertGraph` to not insert new languages.
relate: true
});
关于javascript - 在 Objection.js 中以多对多方式插入额外字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45060991/