Clear ORM
Search…
belongs_to
Belongs to represents an association where the associated object share its primary key in a column of the current object. Let's give an example:
1
CREATE TABLE categories (
2
id bigserial NOT NULL PRIMARY KEY,
3
name text NOT NULL
4
)
5
6
CREATE TABLE posts (
7
id bigserial NOT NULL PRIMARY KEY,
8
name text NOT NULL,
9
content text,
10
category_id bigint NOT NULL
11
)
Copied!
In this case, Post belongs to categories, as it maintain a link to the category through category_id column.
In clear, this relation can be written like this:
1
class Post
2
include Clear::Model
3
4
primary_key
5
6
column name : String
7
column content : String?
8
9
belongs_to category : Category
10
end
11
12
class Category
13
include Clear::Model
14
primary_key
15
16
column name : String
17
18
has_many posts : Post
19
end
Copied!
    Clear will take care for you of the declaration of the column category_id
    You may notice has_many in Category model. We will go further onto it in the next chapter.

Customizing the relation

Clear uses naming convention to infer the name of the foreign key. You may want to override this behavior by adding some parameters:
1
belongs_to relation_name : RelationType,
2
foreign_key: "column_name", primary: true|false,
3
key_type: AnyType?
Copied!
Argument
Description
Default value
foreign_key
The column used by the relation
[underscore_model_name]_id
primary
Set to true if the foreign_key is also the primary key of this table
false
key_type
The type of the column. Set to the primary key type of the relative table.
Int64?
no_cache
Never cache the relation (note: planned feature)
false
Last modified 2yr ago
Copy link