Skip to content

Instantly share code, notes, and snippets.

@sovetnik
Last active May 20, 2017 09:01
Show Gist options
  • Save sovetnik/5a92e03aad3c9180de356f5d3c3176d5 to your computer and use it in GitHub Desktop.
Save sovetnik/5a92e03aad3c9180de356f5d3c3176d5 to your computer and use it in GitHub Desktop.
Reading aggregate
class Book < Hanami::Entity
attributes do
attribute :id, Types::Int
attribute :title, Types::String
attribute :author, Types::String
attribute :publisher, Types::String
end
end
class BookRepository < Hanami::Repository
def all_with_author_and_publisher
books.read query_with_author_and_publisher
end
private
def query_with_author_and_publisher
<<-SQL
SELECT b.id, b.name title, a.name author, p.name publisher
FROM books AS b
JOIN authors AS a ON a.id = b.author_id
JOIN publishers AS p ON p.id = b.publisher_id;
SQL
end
end
CREATE TABLE publishers(
id serial primary key,
name text);
CREATE TABLE authors(
id serial primary key,
name text);
CREATE TABLE books(
id serial primary key,
author_id int references authors(id),
publisher_id int references publishers(id),
name text);
INSERT INTO authors (name) VALUES ('Douglas Adams');
INSERT INTO authors (name) VALUES ('William Gibson');
INSERT INTO publishers (name) VALUES ('Victor Gollancz Ltd');
INSERT INTO publishers (name) VALUES ('GPPutnam Sons');
INSERT INTO publishers (name) VALUES ('Pan Books');
INSERT INTO books (author_id, publisher_id, name) VALUES (1,3,'The Meaning of Liff ');
INSERT INTO books (author_id, publisher_id, name) VALUES (2,1,'Mona Lisa Overdrive');
INSERT INTO books (author_id, publisher_id, name) VALUES (2,2,'Pattern Recognition');
SELECT b.id, b.name title, a.name author, p.name publisher
FROM books AS b
JOIN authors AS a ON a.id = b.author_id
JOIN publishers AS p ON p.id = b.publisher_id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment