Skip to content

Instantly share code, notes, and snippets.

@maracuja
Created July 17, 2020 11:08
Show Gist options
  • Save maracuja/9ee805acbd2a0531a058094695cdbc55 to your computer and use it in GitHub Desktop.
Save maracuja/9ee805acbd2a0531a058094695cdbc55 to your computer and use it in GitHub Desktop.
Polymorphic Association Example
CREATE TABLE linkable (
id serial PRIMARY KEY
);
CREATE TABLE obja (
id integer not null,
name varchar(50) NOT NULL,
FOREIGN KEY(id) REFERENCES linkable(id)
);
CREATE TABLE objb (
id integer not null,
name varchar(50) NOT NULL,
FOREIGN KEY(id) REFERENCES linkable(id)
);
CREATE TABLE carousel_item (
id serial PRIMARY KEY,
name varchar(50),
linkable_id integer not null,
FOREIGN KEY(id) REFERENCES linkable(id)
);
insert into linkable (id) values (1), (2), (3), (4);
insert into obja (id, name) values (1, 'obj 1'), (2, 'obj 2');
insert into objb (id, name) values (3, 'obj 3'), (4, 'obj 4');
insert into carousel_item (id, name, linkable_id)
values
(1, 'carousel item 1', 1),
(2, 'carousel item 2', 3),
(3, 'carousel item 3', 2),
(4, 'carousel item 4', 4);
select * from carousel_item
left join obja on linkable_id=obja.id
left join objb on linkable_id=objb.id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment