onyxframework / sql

A delightful SQL ORM ☺️
https://api.onyxframework.com/sql
MIT License
91 stars 7 forks source link

References with array keys #52

Closed vladfaust closed 6 years ago

vladfaust commented 6 years ago

E.g.

CREATE TABLE tags(
  id SERIAL PRIMARY KEY,
  content VARCHAR(64) NOT NULL,
)

CREATE TABLE posts(
  tag_ids INT[] REFERENCES tags  (id),
);
class Tag
  include Core::Schema

  schema :tags do
    primary_key :id
    reference :posts, Array(Post), foreign_keys: :tag_ids
    field :content, String
  end
end

class Post
  include Core::Schema
  include Core::Query

  schema :posts do
    reference :tags, Array(Tag), keys: :tag_ids
  end
end

Post.join(:tags, select: nil).where("tags.content": "foo")
# => SELECT posts.* FROM posts JOIN tags ON posts.tag_ids @> tags.id WHERE tags.content = ?