Skip to content

Relations

Foreign Keys

You can use the type ForeignKey<T> where T is any type that derives also Model. It will create a reference to the primary key of the model T.

use rorm::prelude::*;

#[derive(Model)]
struct Post {
    #[rorm(id)]
    id: i64,

    creator: ForeignKey<User>,
}

#[derive(Model)]
struct User {
    #[rorm(id)]
    id: i64,
}

Tip

You can point a ForeignKey<T> to the Model its contained in to build self-refenencing structs.

use rorm::prelude::*;

#[derive(Model)]
struct Post {
    #[rorm(id)]
    id: i64,

    creator: ForeignKey<Post>,
}

Foreign keys on non-primary keys

With ForeignKey it is not possible to reference a non-primary key. In order to support this use case, the slightly more verbose ForeignModelByField<T> type was created.

For the generic parameter T, you have to use the provided field!() macro, with the field access syntax.

use rorm::prelude::*;

#[derive(Model)]
struct Post {
    #[rorm(id)]
    id: i64,

    creator_aid: ForeignKeyByField<field!(User::F.another_id)>,
}

#[derive(Model)]
struct User {
    #[rorm(id)]
    id: i64,

    #[rorm(unique)]
    another_id: i64,
}

Backrefs

A backref is the (virtual) reference to be able to query "all items of a specific model with a ForeignKey pointing to the model on which the backref is defined on."

use rorm::prelude::*;

#[derive(Model)]
struct Post {
    #[rorm(id)]
    id: i64,

    creator: ForeignModel<User>,
}

#[derive(Model)]
struct User {
    #[rorm(id)]
    id: i64,

    posts: BackRef<field!(Post::F.creator)>
}

Note

As BackRefs are not a concept of databases, but rather a convenience feature provided by rorm to simplify querying, there's no need to make migrations after the field was added, as it handled internally by rorm.