英文:
Ballerina Persist with 1:N Relation
问题
我有以下的数据模型:
```ballerina
type User record {|
readonly string id;
string name;
int age;
Post[] posts;
|};
type Post record {|
readonly string id;
string title;
string content;
User author;
|};
生成持久化客户端后,我需要检索特定用户的帖子。我尝试了以下代码:
function getPosts(string id) returns db:Post[]|persist:Error? {
db:UserWithRelations user = check dbClient->/users/id;
return user.posts;
}
注意:
db
是通过persist
命令生成的模块。
但是会显示以下错误:
不兼容的类型:预期 'Post[]|ballerina/persist:1.0.0:Error)?',找到 'PostOptionalized[]?'
如果我将函数的返回类型更改为 db:PostOptionalized[]
,则此错误将消失。
造成此错误的原因是什么?是否有一种方法可以检索不带可选字段的 posts
?
<details>
<summary>英文:</summary>
I have the following data model:
type User record {|
readonly string id;
string name;
int age;
Post[] posts;
|};
type Post record {|
readonly string id;
string title;
string content;
User author;
|};
After generating the persist client, I need to retrieve the posts for a particular user. I tried the following:
function getPosts(string id) returns db:Post[]|persist:Error? {
db:UserWithRelations user = check dbClient->/users/id;
return user.posts;
}
> **Note:** `db` is the module generated by persist command.
But this shows the following error:
> incompatible types: expected 'Post[]|ballerina/persist:1.0.0:Error)?', found 'PostOptionalized[]?'
If I change the return type of the function to `db:PostOptionalized[]`, this error goes away.
What is the reason for this error? Is there a way to retrieve the `posts` without optional fields?
</details>
# 答案1
**得分**: 1
你可以根据你需要检索和设置的内容来定义一个自定义的记录类型,如下所示,
```plaintext
type UserWithPosts record {|
db:Post[] posts; // 字段名称应与模型中定义的相同
|}
function getPosts(string id) returns db:Post[]|persist:Error? {
UserWithPosts user = check dbClient->/users/id;
return user.posts;
}
英文:
You can define a custom record type based on what you need to retrieve and set as a target type as follows,
type UserWithPosts record {|
db:Post[] posts; // field name should be same as you defined in the model
|}
function getPosts(string id) returns db:Post[]|persist:Error? {
UserWithPosts user = check dbClient->/users/id;
return user.posts;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论