module

Lustra::Model::HasRelations

class Model
  include Lustra::Model

  has_many posts : Post, foreign_key: Model.underscore_name + "_id", no_cache : false

  has_one passport : Passport
  has_many posts
end

Macros

belongs_to(name, foreign_key = nil, no_cache = false, primary = false, foreign_key_type = Int64, touch = nil, counter_cache = nil)
class Model
  include Lustra::Model

  belongs_to user : User, foreign_key: "the_user_id"
end
Source
has_many(name, through = nil, foreign_key = nil, own_key = nil, primary_key = nil, no_cache = false, polymorphic = false, foreign_key_type = nil, autosave = false)

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 Lustra::Model

  has_many posts : Post, foreign_key: "author_id"
end
Source
has_one(name, foreign_key = nil, primary_key = nil, no_cache = false, polymorphic = false, foreign_key_type = nil, autosave = false)

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
Source