Relacionamentos e Chaves Estrangeiras
Conecte tabelas usando chaves estrangeiras para modelar relacionamentos de um para muitos e de muitos para muitos no seu banco de dados Postgres do Supabase.
Relacionamentos e Chaves Estrangeiras é uma aula grátis de Supabase Backend as a Service no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Supabase Backend as a Service, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Supabase Backend as a Service inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Relationships Matter
Real data is connected: a user has many posts, an order has many items. Relationships link rows across tables so you avoid duplicating data.
What Is a Foreign Key?
A foreign key is a column that points to the primary key of another table. It enforces that the referenced row actually exists.
One-to-Many Example
One author writes many books. The books table stores the author's id.
CREATE TABLE authors (
id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
name text NOT NULL
);
CREATE TABLE books (
id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
title text NOT NULL,
author_id bigint REFERENCES authors(id)
);Referential Integrity
Postgres will reject inserting a book with an author_id that does not exist. This keeps your data consistent.
ON DELETE Behavior
Decide what happens when a parent row is deleted:
CASCADEdeletes the children tooSET NULLclears the referenceRESTRICTblocks the delete
ALTER TABLE books
ADD CONSTRAINT fk_author
FOREIGN KEY (author_id)
REFERENCES authors(id)
ON DELETE CASCADE;Querying Across Tables
With the Supabase client you can fetch related rows in one call using nested selects.
const { data } = await supabase
.from('authors')
.select('name, books(title)');Many-to-Many Relationships
When both sides can have many of the other (students and courses), use a join table holding both foreign keys.
CREATE TABLE enrollments (
student_id bigint REFERENCES students(id),
course_id bigint REFERENCES courses(id),
PRIMARY KEY (student_id, course_id)
);Composite Primary Keys
In a join table the pair of foreign keys often forms the primary key, preventing duplicate links between the same two rows.
Naming Conventions
A common convention names foreign keys as singular_id (e.g. author_id). Consistency makes nested queries predictable.
function fkName(table) {
return table.replace(/s$/, '') + '_id';
}
console.log(fkName('authors'));Visualizing in the Dashboard
The Supabase Table Editor shows relationship links, and the Schema Visualizer draws how your tables connect, which helps verify your design.
Putting It Together
Model connections with foreign keys, choose sensible ON DELETE rules, and use join tables for many-to-many. This is the backbone of a clean schema.
Quick Check
Test your understanding of relationships.
Recap
You learned foreign keys, one-to-many vs many-to-many relationships, ON DELETE behaviors, join tables with composite keys, and how to query related data with nested selects.
Perguntas Frequentes
A aula “Relacionamentos e Chaves Estrangeiras” é grátis?
Sim — o texto completo de “Relacionamentos e Chaves Estrangeiras” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Supabase Backend as a Service, atualize para CoddyKit PRO. O curso de Supabase Backend as a Service inclui 4 aulas no total.
O que vou aprender em “Relacionamentos e Chaves Estrangeiras”?
Conecte tabelas usando chaves estrangeiras para modelar relacionamentos de um para muitos e de muitos para muitos no seu banco de dados Postgres do Supabase. Você pratica Supabase Backend as a Service com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Supabase Backend as a Service?
Nenhuma experiência prévia é necessária. Supabase Backend as a Service no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Relacionamentos e Chaves Estrangeiras”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Supabase Backend as a Service?
Sim. Cada aula de Supabase Backend as a Service inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Projeto de esquemas de banco de dados
- Criação de tabelas e colunas
- Inserção e consulta básicas de dados
- Relacionamentos e Chaves Estrangeiras