Ballerina 持久化与1:N关系

huangapple go评论57阅读模式
英文:

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;
}


&gt; **Note:** `db` is the module generated by persist command.

But this shows the following error:

&gt; incompatible types: expected &#39;Post[]|ballerina/persist:1.0.0:Error)?&#39;, found &#39;PostOptionalized[]?&#39;

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-&gt;/users/id;
    return user.posts;
}

huangapple
  • 本文由 发表于 2023年6月8日 16:58:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定