Ballerina 持久化与1:N关系

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

Ballerina Persist with 1:N Relation

问题

  1. 我有以下的数据模型:
  2. ```ballerina
  3. type User record {|
  4. readonly string id;
  5. string name;
  6. int age;
  7. Post[] posts;
  8. |};
  9. type Post record {|
  10. readonly string id;
  11. string title;
  12. string content;
  13. User author;
  14. |};

生成持久化客户端后,我需要检索特定用户的帖子。我尝试了以下代码:

  1. function getPosts(string id) returns db:Post[]|persist:Error? {
  2. db:UserWithRelations user = check dbClient->/users/id;
  3. return user.posts;
  4. }

注意: db 是通过 persist 命令生成的模块。

但是会显示以下错误:

不兼容的类型:预期 'Post[]|ballerina/persist:1.0.0:Error)?',找到 'PostOptionalized[]?'

如果我将函数的返回类型更改为 db:PostOptionalized[],则此错误将消失。

造成此错误的原因是什么?是否有一种方法可以检索不带可选字段的 posts

  1. <details>
  2. <summary>英文:</summary>
  3. 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;
|};

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

  1. &gt; **Note:** `db` is the module generated by persist command.
  2. But this shows the following error:
  3. &gt; incompatible types: expected &#39;Post[]|ballerina/persist:1.0.0:Error)?&#39;, found &#39;PostOptionalized[]?&#39;
  4. If I change the return type of the function to `db:PostOptionalized[]`, this error goes away.
  5. What is the reason for this error? Is there a way to retrieve the `posts` without optional fields?
  6. </details>
  7. # 答案1
  8. **得分**: 1
  9. 你可以根据你需要检索和设置的内容来定义一个自定义的记录类型,如下所示,
  10. ```plaintext
  11. type UserWithPosts record {|
  12. db:Post[] posts; // 字段名称应与模型中定义的相同
  13. |}
  14. function getPosts(string id) returns db:Post[]|persist:Error? {
  15. UserWithPosts user = check dbClient->/users/id;
  16. return user.posts;
  17. }
英文:

You can define a custom record type based on what you need to retrieve and set as a target type as follows,

  1. type UserWithPosts record {|
  2. db:Post[] posts; // field name should be same as you defined in the model
  3. |}
  4. function getPosts(string id) returns db:Post[]|persist:Error? {
  5. UserWithPosts user = check dbClient-&gt;/users/id;
  6. return user.posts;
  7. }

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:

确定