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:
CREATE TABLE categories (id bigserial NOT NULL PRIMARY KEY,name text NOT NULL)CREATE TABLE posts (id bigserial NOT NULL PRIMARY KEY,name text NOT NULL,content text,category_id bigint NOT NULL)
In this case, Post belongs to categories, as it maintain a link to the category through
In clear, this relation can be written like this:
class Postinclude Clear::Modelprimary_keycolumn name : Stringcolumn content : String?belongs_to category : Categoryendclass Categoryinclude Clear::Modelprimary_keycolumn name : Stringhas_many posts : Postend
Clear will take care for you of the declaration of the column
You may notice
has_many in Category model. We will go further onto it in the next chapter.
Clear uses naming convention to infer the name of the foreign key. You may want to override this behavior by adding some parameters:
belongs_to relation_name : RelationType,foreign_key: "column_name", primary: true|false,key_type: AnyType?
The column used by the relation
Set to true if the foreign_key is also the primary key of this table
The type of the column. Set to the primary key type of the relative table.
Never cache the relation (note: planned feature)