如何插入Description并关联Experience后返回其ID?
插入Description并关联Experience后返回其ID
数据模型Schema
module default { type Experience { property employer -> str; property position -> str; property time -> str; property active -> bool { default := true; }; multi link descriptions -> Description { constraint exclusive }; property priority -> int32; } type Description { required property description -> str; property priority -> int32; } }
需求
插入一条Description记录,关联到指定ID的Experience记录,同时获取这条新插入的Description的ID。
原代码问题
原查询中,update语句会返回被更新的Experience对象,后续的select newDescription.id不会生效——因为EdgeQL查询的最终结果由最后一个执行的语句决定。
解决代码
调整查询结构,将update放入with块,最后直接返回新插入记录的ID:
with newDescription := ( insert Description { description := <optional str>$description } ), -- 执行关联操作,结果可忽略 _ := ( update Experience filter .id = <uuid>$id set { descriptions += newDescription } ) select newDescription.id;
这里用_作为变量名,表示我们不需要使用这个更新操作的返回值,最后通过select newDescription.id直接返回新插入的Description的ID,完全符合需求。
内容的提问来源于stack exchange,提问作者Kyle Johnson
相关产品推荐
相关产品推荐

