Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for 1 to many relationships #30

Closed
drujensen opened this issue Apr 29, 2017 · 6 comments
Closed

add support for 1 to many relationships #30

drujensen opened this issue Apr 29, 2017 · 6 comments

Comments

@drujensen
Copy link
Member

Create two new macros: belongs_to and has_many

require "./post"

class Comment < Kemalyst::Model
  belongs_to post
  ...
end

This will create a mapping to the post_id : Int64 field and generate a method that will query the parent and return it.

def post
  Post.find post_id
end
require "./comment"

class Post < Kemalyst::Model
  has_many comments
  ...
end

This will create a method called comments that will query the children records.

def comments
  Comments.all("JOIN posts ON posts.id = comments.post_id WHERE posts.id = ?", id)
end

Options to override the field names and types should be considered for legacy database mappings.

One of the difficulties is requiring the other model. Macros do not allow you to inject require into the class.

Another issue is the N+1 queries for comments. I think we can find ways of optimizing this later.

@elorest
Copy link
Member

elorest commented May 5, 2017

I would suggest that all of the models should be loaded into the main project file.

#src/blog.cr
require "./models/*"

@drujensen
Copy link
Member Author

drujensen commented May 5, 2017

can you require all subdirectories as well? does this work in crystal? require "./models/**/*"

@drujensen
Copy link
Member Author

found it: https://crystal-lang.org/docs/syntax_and_semantics/requiring_files.html

require "./models/**"

@elorest
Copy link
Member

elorest commented May 5, 2017

Both of those will work.

@andrewzah
Copy link
Contributor

I'll try and take a stab at this in the next few weeks.

@migeorge
Copy link
Contributor

Closing since #52 was merged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
No open projects
Development

No branches or pull requests

5 participants