How to create a many to many relation in Objectbox in fbs file

Viewed 94

This is my database.fsb file

table Author {
    /// objectbox:id
    id:ulong;
    text:string;
}

table Book{
    /// objectbox:id
    id: ulong;
    name: string;

    /// objectbox:relation(name=authors,to=Author)
    authors:ulong;
}

What type I must use for authors in Book table to make a many-to-many relation between book and authors?

2 Answers

There is no built-in many-to-many relationship in FlatBuffers, as that would constitute a graph, and FlatBuffers cannot do cycles, only trees/dags.

You could use authors:[Author], but you cannot then also add a books:[Book] to Author as that would create a cycle. So you have to pick one of the two, and re-construct the opposite relation when you're reading the data.

First some background: a many-to-many relation in the ObjectBox database holds its data "outside" of the entities (in a separate data "bucket"; the pendant to a "table" of a relational database).

Thus, that relation annotation is already sufficient.

You did not indicate which language you are using, but both C and C++ ObjectBox APIs do not have wrapper types for relations (e.g. lists as used in higher level languages). Instead, you must use the low-level functions obx_cursor_rel_put, obx_cursor_rel_remove, and obx_cursor_rel_ids. Or, the box-based functions like obx_box_rel_put.

To give you an impression, check the following gist: https://gist.github.com/greenrobot/552f560a92737ec045b0efdc2122fd62 - you cannot run it as because it lacks the testing context, but should give you an idea of how to use it.

Related