gpt4 book ai didi

node.js - 如何在不创建模型的情况下插入对模型的引用?

转载 作者:太空宇宙 更新时间:2023-11-03 23:58:32 30 4
gpt4 key购买 nike

我的模型 A 可以关联一行或多行模型 B。这种关系只能单向发展。

我跑了:

result = await A.query()
.where('id', 123) // 123 is an already existing model A
.insertGraph([
{
B: [{id: 456}] // 456 is an already existing model B
}
]);

但我收到错误Key (id)=(456)已经存在。

据我了解,Objection 试图创建一个 ID 为 456 的新模型 B,我只想在 A:123 和 B:456 两行之间添加关系。

最佳答案

既然您正在更新,我就不会使用insertGraph()。可以使用 refs 通过 upsertGraph() 来完成。但这个方法有点复杂,理想情况下我会这样做:

const a = await A
.query()
.findById(123);

const numRelatedRows = await a.$relatedQuery('B')
.relate(456)

使用 upsertGraph(),您可以通过这种方式关联子项 456,但子项的其余部分(如果存在)将不相关。您可以使用很多选项修改 upsert 的行为,但对我来说,在您的情况下 $latedQuery() 是正确的方法:

const result = await A.upsertGraphAndFetch(
{
id: 123,
B: [
{#ref: 456} // relate 456, and unrelate the rest, since not present here
]
}
)

关于node.js - 如何在不创建模型的情况下插入对模型的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55877887/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com