我有以下数据模型:

type User record {|
    readonly string id;
    string name;
    int age;
    Post[] posts;
|};

type Post record {|
    readonly string id;
    string title;
    string content;
    User author;
|};

在生成持久化客户端之后,我需要检索特定用户的帖子.我try 了以下几种方法:

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

Note: db是持久化命令生成的模块.

但这会显示以下错误:

不兼容的类型:应为‘Post[]|Ballerina/Persistent:1.0.0:Error)?’,找到‘PostOptionalized[]?’

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

这个错误的原因是什么?有没有办法在没有可选字段的情况下检索posts

推荐答案

您可以根据需要检索的内容定义一个自定义记录类型,并设置为目标类型,如下所示.

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

Database相关问答推荐

使用 Npgsql 执行年龄查询并在 .NET 应用程序中返回结果?

只用一个 save() 插入多行

数据库内部—从哪里开始?

在 Oracle 的 Check 语句中使用子查询

库存数据库的最佳 struct

错误:mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication

Django:如何以线程安全的方式执行 get_or_create()?

是否有任何数据库支持自动索引创建?

连接字符串中超时

Redis: Get key and value on expiration

如何从 T-SQL 中的表中 Select 前 N 行?

Django Atomic Transaction 是否锁定数据库?

MySQL中的eq_ref和ref类型是什么意思解释

SQL 查询 - 如何按 null 或不为 null 进行过滤

将查询限制为一条记录会提高性能吗

如何使用反射调用扫描可变参数函数

在 MYSQL 的子查询中使用 LIMIT 关键字的替代方法

分离实体和被管理实体

Spring data : CrudRepository 的保存方法和更新

将 NULL 插入 MySQL 时间戳