Relations

Ballerina ORM supports common relational mappings through @orm:Relation.

Relation types

  • orm:ONE_TO_ONE
  • orm:ONE_TO_MANY
  • orm:MANY_TO_ONE
  • orm:MANY_TO_MANY

ONE_TO_MANY + MANY_TO_ONE

ballerina
@orm:Entity {tableName: "users"}
public type User record {|
    @orm:Id @orm:AutoIncrement
    int id;

    string name;

    @orm:Relation {'type: orm:ONE_TO_MANY}
    Post[]? posts;
|};

@orm:Entity {tableName: "posts"}
public type Post record {|
    @orm:Id @orm:AutoIncrement
    int id;

    string title;

    @orm:Column {nullable: false}
    int authorId;

    @orm:Relation {
        'type: orm:MANY_TO_ONE,
        references: ["id"],
        foreignKey: ["authorId"]
    }
    User? author;
|};

MANY_TO_MANY

ballerina
@orm:Entity {tableName: "posts"}
public type Post record {|
    @orm:Id @orm:AutoIncrement
    int id;

    string title;

    @orm:Relation {
        'type: orm:MANY_TO_MANY,
        joinTable: "post_categories"
    }
    Category[]? categories;
|};

Eager loading with include

ballerina
var users = check db.'from(User)
    .include({posts: true})
    .findMany();

Foreign key conventions

  • use explicit integer key fields (for example authorId)
  • keep references aligned with target primary or unique key names
  • use joinTable for many-to-many mappings

Next step

Continue with Filtering.