module Clear::Model::HasRelations
Overview
class Model
include Clear::Model
has_many posts : Post, foreign_key: Model.underscore_name + "_id", no_cache : false
has_one passport : Passport
has_many posts
end
Direct including types
Defined in:
clear/model/modules/has_relations.crMacro Summary
-
belongs_to(name, foreign_key = nil, no_cache = false, primary = false, foreign_key_type = Int64)
-
has_many(name, through = nil, foreign_key = nil, own_key = nil, primary_key = nil, no_cache = false, polymorphic = false, foreign_key_type = nil)
Has Many and Has One are the relations where the model share its primary key into a foreign table.
-
has_one(name, foreign_key = nil, primary_key = nil, no_cache = false, polymorphic = false, foreign_key_type = nil)
The method
has_one
declare a relation 1 to [0,1] where the current model primary key is stored in the foreign table.
Macro Detail
class Model
include Clear::Model
belongs_to user : User, foreign_key: "the_user_id"
end
Has Many and Has One are the relations where the model share its primary key into a foreign table. In our example above, we can assume than a User has many Post as author.
Basically, for each belongs_to
declaration, you must have a has_many
or has_one
declaration on the other model.
While has_many
relation returns a list of models, has_one
returns only one model when called.
Example:
class User
include Clear::Model
has_many posts : Post, foreign_key: "author_id"
end
The method has_one
declare a relation 1 to [0,1]
where the current model primary key is stored in the foreign table.
primary_key
method (default: self#__pkey__
) and foreign_key
method
(default: table_name in singular, plus "_id" appended)
can be redefined
Example:
model Passport
column id : Int32, primary : true
has_one user : User It assumes the table `users` have a column `passport_id`
end
model Passport
column id : Int32, primary : true
has_one owner : User # It assumes the table `users` have a column `passport_id`
end