Programming Search⌘K

Patterncore

Association Table Mapping

Also called association table mapping pattern, join table mapping, many-to-many mapping, link table.

An Association Table Mapping saves a many-to-many association between objects as a separate link table, in which each row holds the keys of one pair of linked rows.

Family
architectural
Intent
Saves an association as a table with foreign keys to the tables that are linked by the association.

Intent

An Association Table Mapping "Saves an association as a table with foreign keys to the tables that are linked by the association."1 Each row of the link table joins one row on one side to one row on the other side.

Problem

"Objects can handle multivalued fields quite easily by using collections as field values. Relational databases don't have this feature and are constrained to single-valued fields only."1 For a one-to-many association, a Foreign Key Mapping puts the key in the table on the single-valued side. An employee has many skills, and a skill belongs to many employees. Fowler explains why a foreign key cannot do this: "a many-to-many association can't do this because there is no single-valued end to hold the foreign key."1

Solution

"The answer is the classic resolution that's been used by relational data people for decades: create an extra table to record the relationship."1 Wikipedia describes the same design: "A relational database requires the implementation of a base relation (or base table ) to resolve many-to-many relationships", and a base relation of this kind "is called, informally, an associative table".2

The link table has two foreign key columns, one for each side. Each row stands for one link. The two keys together are the primary key of the link table, so one pair cannot appear twice. SQLAlchemy recommends this: the two columns should be "established within either a unique constraint or more commonly as the primary key constraint", which "ensures that duplicate rows won’t be persisted within the table regardless of issues on the application side".3

  memory                               database
  Ann.skills = [Python, SQL]           employee(1, Ann)     skill(1, Python)
  Bo.skills  = [Python]                employee(2, Bo)      skill(2, SQL)
                                       employee_skill(employee_id, skill_id)
                                         (1, 1)  (1, 2)  (2, 1)
  load Ann.skills:  SELECT ... FROM skill JOIN employee_skill ... WHERE employee_id = 1
  load Python's employees: the same table, read from the other side

The participants are the two entity tables, the link table with a pair of keys in each row, and the mapper, which writes link rows when it saves a collection and joins through the link table when it loads one.

The following program saves two employees with their skills, and loads the association from both sides through the same link table.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table employee (id integer primary key, name text);
create table skill (id integer primary key, name text);
create table employee_skill (
    employee_id integer references employee(id),
    skill_id integer references skill(id),
    primary key (employee_id, skill_id));
insert into skill (name) values ('Python'), ('SQL');
""")


class Employee:
    def __init__(self, name, skills, id=None):
        self.id, self.name = id, name
        self.skills = skills  # A list of skill keys in memory: many-to-many.


def save(e):
    if e.id is None:
        e.id = db.execute("insert into employee (name) values (?)", (e.name,)).lastrowid
    # The link table holds one row for each pair (employee, skill).
    db.execute("delete from employee_skill where employee_id = ?", (e.id,))
    db.executemany("insert into employee_skill values (?, ?)", [(e.id, s) for s in e.skills])


def skills_of(employee_id):
    sql = """select s.name from skill s join employee_skill es on es.skill_id = s.id
             where es.employee_id = ? order by s.id"""
    return [n for (n,) in db.execute(sql, (employee_id,))]


def employees_with(skill_id):
    sql = """select e.name from employee e join employee_skill es on es.employee_id = e.id
             where es.skill_id = ? order by e.id"""
    return [n for (n,) in db.execute(sql, (skill_id,))]


save(Employee("Ann", [1, 2]))
save(Employee("Bo", [1]))
print(db.execute("select * from employee_skill order by 1, 2").fetchall())
print("Ann:", ", ".join(skills_of(1)))
print("Python:", ", ".join(employees_with(1)))
Output
[(1, 1), (1, 2), (2, 1)]
Ann: Python, SQL
Python: Ann, Bo

This save writes the collection by deleting all the link rows of the employee and inserting them again. Fowler's book describes this simple way to save the links.4 It is correct because a link row has no data and no other table refers to it.

Example

Each example file saves two employees and their skills, and prints the link rows as pairs of keys. It loads the skills of Ann, and the employees who know Python, from the same rows. It then changes the skills of Ann and saves the collection by comparing it with the link rows: one pair is deleted and one is inserted, and the other rows stay. The last line tries to insert a pair that is already there, and the primary key of the link table stops it. The Python file uses SQLite. The JavaScript, Java, Go and Rust files keep the link table in memory as a set of pairs, which also rejects a duplicate pair.

PythonGitHub
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table employee (id integer primary key, name text);
create table skill (id integer primary key, name text);
create table employee_skill (
    employee_id integer references employee(id),
    skill_id integer references skill(id),
    primary key (employee_id, skill_id));
insert into skill (name) values ('Python'), ('SQL'), ('Go');
""")


class Employee:
    def __init__(self, name, skills, id=None):
        self.id, self.name, self.skills = id, name, skills  # skills: a list of skill keys


def insert(e):
    e.id = db.execute("insert into employee (name) values (?)", (e.name,)).lastrowid
    for s in e.skills:
        db.execute("insert into employee_skill values (?, ?)", (e.id, s))


def update_skills(e):
    # Compare the collection with the link rows: insert the new pairs, delete the old ones.
    sql = "select skill_id from employee_skill where employee_id = ?"
    in_db = {s for (s,) in db.execute(sql, (e.id,))}
    added = [s for s in e.skills if s not in in_db]
    removed = sorted(in_db - set(e.skills))
    for s in added:
        db.execute("insert into employee_skill values (?, ?)", (e.id, s))
    for s in removed:
        db.execute("delete from employee_skill where employee_id = ? and skill_id = ?", (e.id, s))
    return len(removed), len(added)


def skills_of(employee_id):
    sql = """select s.name from skill s join employee_skill es on es.skill_id = s.id
             where es.employee_id = ? order by s.id"""
    return ", ".join(n for (n,) in db.execute(sql, (employee_id,)))


def employees_with(skill_id):
    sql = """select e.name from employee e join employee_skill es on es.employee_id = e.id
             where es.skill_id = ? order by e.id"""
    return ", ".join(n for (n,) in db.execute(sql, (skill_id,)))


def links():
    rows = db.execute("select employee_id, skill_id from employee_skill order by 1, 2")
    return " ".join(f"{e}-{s}" for e, s in rows)


ann = Employee("Ann", [1, 2])
insert(ann)
insert(Employee("Bo", [1]))
print("links:", links())
print("Ann:", skills_of(1))
print("Python:", employees_with(1))

ann.skills = [2, 3]
deleted, inserted = update_skills(ann)
print(f"update Ann: deleted {deleted}, inserted {inserted}")
print("links:", links())
print("Ann:", skills_of(1))

try:
    db.execute("insert into employee_skill values (2, 1)")
except sqlite3.IntegrityError as e:
    print("link 2-1 again:", e)
Output
links: 1-1 1-2 2-1
Ann: Python, SQL
Python: Ann, Bo
update Ann: deleted 1, inserted 1
links: 1-2 1-3 2-1
Ann: SQL, Go
link 2-1 again: UNIQUE constraint failed: employee_skill.employee_id, employee_skill.skill_id
  • Verdict: idiom. The link table employee_skill has two foreign keys and a primary key on the pair, so SQLite rejects a second row for the same pair with an IntegrityError.
  • update_skills reads the keys of the link rows, inserts the pairs that are new and deletes the pairs that are gone. The other rows stay as they are.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;

public class Main {
    record Link(long employeeId, long skillId) implements Comparable<Link> {
        public int compareTo(Link o) {
            int c = Long.compare(employeeId, o.employeeId);
            return c != 0 ? c : Long.compare(skillId, o.skillId);
        }
    }

    // A stand-in for the database: two entity tables and a link table of key pairs.
    static final Map<Long, String> EMPLOYEE = new TreeMap<>();
    static final Map<Long, String> SKILL = new TreeMap<>(Map.of(1L, "Python", 2L, "SQL", 3L, "Go"));
    static final TreeSet<Link> EMPLOYEE_SKILL = new TreeSet<>(); // Sorted by both keys, like a primary key.
    static long lastEmployee = 0;

    static void insertLink(long employeeId, long skillId) {
        if (!EMPLOYEE_SKILL.add(new Link(employeeId, skillId))) {
            throw new IllegalStateException("UNIQUE constraint failed: employee_skill.employee_id, employee_skill.skill_id");
        }
    }

    static class Employee {
        Long id;
        String name;
        List<Long> skills; // A list of skill keys.

        Employee(String name, List<Long> skills) {
            this.name = name;
            this.skills = skills;
        }
    }

    static void insert(Employee e) {
        EMPLOYEE.put(++lastEmployee, e.name);
        e.id = lastEmployee;
        for (long s : e.skills) {
            insertLink(e.id, s);
        }
    }

    static int[] updateSkills(Employee e) {
        // Compare the collection with the link rows: insert the new pairs, delete the old ones.
        List<Long> inDb = new ArrayList<>();
        for (Link l : EMPLOYEE_SKILL) {
            if (l.employeeId() == e.id) {
                inDb.add(l.skillId());
            }
        }
        List<Long> added = new ArrayList<>();
        for (long s : e.skills) {
            if (!inDb.contains(s)) {
                added.add(s);
            }
        }
        List<Long> removed = new ArrayList<>();
        for (long s : inDb) {
            if (!e.skills.contains(s)) {
                removed.add(s);
            }
        }
        for (long s : added) {
            insertLink(e.id, s);
        }
        for (long s : removed) {
            EMPLOYEE_SKILL.remove(new Link(e.id, s));
        }
        return new int[] {removed.size(), added.size()};
    }

    static String skillsOf(long employeeId) {
        List<String> names = new ArrayList<>();
        for (Link l : EMPLOYEE_SKILL) {
            if (l.employeeId() == employeeId) {
                names.add(SKILL.get(l.skillId()));
            }
        }
        return String.join(", ", names);
    }

    static String employeesWith(long skillId) {
        List<String> names = new ArrayList<>();
        for (Link l : EMPLOYEE_SKILL) {
            if (l.skillId() == skillId) {
                names.add(EMPLOYEE.get(l.employeeId()));
            }
        }
        return String.join(", ", names);
    }

    static String links() {
        List<String> parts = new ArrayList<>();
        for (Link l : EMPLOYEE_SKILL) {
            parts.add(l.employeeId() + "-" + l.skillId());
        }
        return String.join(" ", parts);
    }

    public static void main(String[] args) {
        Employee ann = new Employee("Ann", List.of(1L, 2L));
        insert(ann);
        insert(new Employee("Bo", List.of(1L)));
        System.out.println("links: " + links());
        System.out.println("Ann: " + skillsOf(1));
        System.out.println("Python: " + employeesWith(1));

        ann.skills = List.of(2L, 3L);
        int[] counts = updateSkills(ann);
        System.out.println("update Ann: deleted " + counts[0] + ", inserted " + counts[1]);
        System.out.println("links: " + links());
        System.out.println("Ann: " + skillsOf(1));

        try {
            insertLink(2, 1);
        } catch (IllegalStateException ex) {
            System.out.println("link 2-1 again: " + ex.getMessage());
        }
    }
}
Output
links: 1-1 1-2 2-1
Ann: Python, SQL
Python: Ann, Bo
update Ann: deleted 1, inserted 1
links: 1-2 1-3 2-1
Ann: SQL, Go
link 2-1 again: UNIQUE constraint failed: employee_skill.employee_id, employee_skill.skill_id
  • Verdict: idiom. A link row is a record that is Comparable, and the link table is a TreeSet of these records, so the rows iterate in key order and add returns false for a pair that is already there.
  • With JPA or Hibernate, @ManyToMany and @JoinTable declare the same link table, and the provider writes the link rows.
JavaScriptGitHub
// A stand-in for the database: two entity tables and a link table of [employeeId, skillId] pairs.
const employeeTable = new Map();
const skillTable = new Map([[1, "Python"], [2, "SQL"], [3, "Go"]]);
const employeeSkill = new Set(); // Each key is "employeeId-skillId", like a two-column primary key.
let lastEmployee = 0;

function insertLink(employeeId, skillId) {
  const key = `${employeeId}-${skillId}`;
  if (employeeSkill.has(key)) {
    throw new Error("UNIQUE constraint failed: employee_skill.employee_id, employee_skill.skill_id");
  }
  employeeSkill.add(key);
}

function linkRows() {
  return [...employeeSkill]
    .map((k) => k.split("-").map(Number))
    .sort((a, b) => a[0] - b[0] || a[1] - b[1]);
}

class Employee {
  constructor(name, skills, id = null) {
    this.id = id;
    this.name = name;
    this.skills = skills; // A list of skill keys.
  }
}

function insert(e) {
  lastEmployee += 1;
  employeeTable.set(lastEmployee, e.name);
  e.id = lastEmployee;
  for (const s of e.skills) insertLink(e.id, s);
}

function updateSkills(e) {
  // Compare the collection with the link rows: insert the new pairs, delete the old ones.
  const inDb = linkRows().filter(([emp]) => emp === e.id).map(([, s]) => s);
  const added = e.skills.filter((s) => !inDb.includes(s));
  const removed = inDb.filter((s) => !e.skills.includes(s));
  for (const s of added) insertLink(e.id, s);
  for (const s of removed) employeeSkill.delete(`${e.id}-${s}`);
  return [removed.length, added.length];
}

function skillsOf(employeeId) {
  return linkRows()
    .filter(([emp]) => emp === employeeId)
    .map(([, s]) => skillTable.get(s))
    .join(", ");
}

function employeesWith(skillId) {
  return linkRows()
    .filter(([, s]) => s === skillId)
    .map(([emp]) => employeeTable.get(emp))
    .join(", ");
}

function links() {
  return linkRows()
    .map(([emp, s]) => `${emp}-${s}`)
    .join(" ");
}

const ann = new Employee("Ann", [1, 2]);
insert(ann);
insert(new Employee("Bo", [1]));
console.log(`links: ${links()}`);
console.log(`Ann: ${skillsOf(1)}`);
console.log(`Python: ${employeesWith(1)}`);

ann.skills = [2, 3];
const [deleted, inserted] = updateSkills(ann);
console.log(`update Ann: deleted ${deleted}, inserted ${inserted}`);
console.log(`links: ${links()}`);
console.log(`Ann: ${skillsOf(1)}`);

try {
  insertLink(2, 1);
} catch (e) {
  console.log(`link 2-1 again: ${e.message}`);
}
Output
links: 1-1 1-2 2-1
Ann: Python, SQL
Python: Ann, Bo
update Ann: deleted 1, inserted 1
links: 1-2 1-3 2-1
Ann: SQL, Go
link 2-1 again: UNIQUE constraint failed: employee_skill.employee_id, employee_skill.skill_id
  • Verdict: idiom. The link table is a Set of keys in the form "employeeId-skillId", so the pair works like a two-column primary key, and insertLink throws for a pair that is already there.
  • skillsOf and employeesWith read the same set from the two sides, as the two joins do in SQL.
package main

import (
	"errors"
	"fmt"
	"slices"
	"sort"
	"strings"
)

type link struct{ employeeID, skillID int64 }

// A stand-in for the database: two entity tables and a link table of key pairs.
var (
	employeeTable = map[int64]string{}
	skillTable    = map[int64]string{1: "Python", 2: "SQL", 3: "Go"}
	employeeSkill = map[link]bool{} // The pair is the key, like a two-column primary key.
	lastEmployee  int64
)

func insertLink(employeeID, skillID int64) error {
	l := link{employeeID, skillID}
	if employeeSkill[l] {
		return errors.New("UNIQUE constraint failed: employee_skill.employee_id, employee_skill.skill_id")
	}
	employeeSkill[l] = true
	return nil
}

func linkRows() []link {
	rows := make([]link, 0, len(employeeSkill))
	for l := range employeeSkill {
		rows = append(rows, l)
	}
	sort.Slice(rows, func(i, j int) bool {
		if rows[i].employeeID != rows[j].employeeID {
			return rows[i].employeeID < rows[j].employeeID
		}
		return rows[i].skillID < rows[j].skillID
	})
	return rows
}

type Employee struct {
	ID     int64
	Name   string
	Skills []int64 // A list of skill keys.
}

func insert(e *Employee) error {
	lastEmployee++
	employeeTable[lastEmployee] = e.Name
	e.ID = lastEmployee
	for _, s := range e.Skills {
		if err := insertLink(e.ID, s); err != nil {
			return err
		}
	}
	return nil
}

func updateSkills(e *Employee) (deleted, inserted int, err error) {
	// Compare the collection with the link rows: insert the new pairs, delete the old ones.
	var inDB []int64
	for _, l := range linkRows() {
		if l.employeeID == e.ID {
			inDB = append(inDB, l.skillID)
		}
	}
	for _, s := range e.Skills {
		if !slices.Contains(inDB, s) {
			if err := insertLink(e.ID, s); err != nil {
				return deleted, inserted, err
			}
			inserted++
		}
	}
	for _, s := range inDB {
		if !slices.Contains(e.Skills, s) {
			delete(employeeSkill, link{e.ID, s})
			deleted++
		}
	}
	return deleted, inserted, nil
}

func skillsOf(employeeID int64) string {
	var names []string
	for _, l := range linkRows() {
		if l.employeeID == employeeID {
			names = append(names, skillTable[l.skillID])
		}
	}
	return strings.Join(names, ", ")
}

func employeesWith(skillID int64) string {
	var names []string
	for _, l := range linkRows() {
		if l.skillID == skillID {
			names = append(names, employeeTable[l.employeeID])
		}
	}
	return strings.Join(names, ", ")
}

func links() string {
	var parts []string
	for _, l := range linkRows() {
		parts = append(parts, fmt.Sprintf("%d-%d", l.employeeID, l.skillID))
	}
	return strings.Join(parts, " ")
}

func main() {
	ann := &Employee{Name: "Ann", Skills: []int64{1, 2}}
	if err := insert(ann); err != nil {
		fmt.Println(err)
	}
	if err := insert(&Employee{Name: "Bo", Skills: []int64{1}}); err != nil {
		fmt.Println(err)
	}
	fmt.Println("links:", links())
	fmt.Println("Ann:", skillsOf(1))
	fmt.Println("Python:", employeesWith(1))

	ann.Skills = []int64{2, 3}
	deleted, inserted, err := updateSkills(ann)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("update Ann: deleted %d, inserted %d\n", deleted, inserted)
	fmt.Println("links:", links())
	fmt.Println("Ann:", skillsOf(1))

	if err := insertLink(2, 1); err != nil {
		fmt.Println("link 2-1 again:", err)
	}
}
Output
links: 1-1 1-2 2-1
Ann: Python, SQL
Python: Ann, Bo
update Ann: deleted 1, inserted 1
links: 1-2 1-3 2-1
Ann: SQL, Go
link 2-1 again: UNIQUE constraint failed: employee_skill.employee_id, employee_skill.skill_id
  • Verdict: idiom. A link row is a struct of two keys, and the link table is a map[link]bool, so the pair is the key of the map. Go maps have no order, so linkRows sorts the pairs before it prints them.
  • insertLink and updateSkills return an error for a duplicate pair, as a database driver returns the error of the constraint.
RustGitHub
use std::collections::{BTreeMap, BTreeSet};

// A stand-in for the database: two entity tables and a link table of key pairs.
struct Db {
    employee: BTreeMap<i64, String>,
    skill: BTreeMap<i64, String>,
    employee_skill: BTreeSet<(i64, i64)>, // Sorted by both keys, like a primary key.
    last_employee: i64,
}

struct Employee {
    id: Option<i64>,
    name: String,
    skills: Vec<i64>, // A list of skill keys.
}

impl Db {
    fn insert_link(&mut self, employee_id: i64, skill_id: i64) -> Result<(), String> {
        if !self.employee_skill.insert((employee_id, skill_id)) {
            return Err("UNIQUE constraint failed: employee_skill.employee_id, employee_skill.skill_id".to_string());
        }
        Ok(())
    }

    fn insert(&mut self, e: &mut Employee) -> Result<(), String> {
        self.last_employee += 1;
        self.employee.insert(self.last_employee, e.name.clone());
        e.id = Some(self.last_employee);
        for &s in &e.skills {
            self.insert_link(self.last_employee, s)?;
        }
        Ok(())
    }

    fn update_skills(&mut self, e: &Employee) -> Result<(usize, usize), String> {
        // Compare the collection with the link rows: insert the new pairs, delete the old ones.
        let id = e.id.ok_or("not saved")?;
        let in_db: Vec<i64> = self.employee_skill.iter().filter(|(emp, _)| *emp == id).map(|(_, s)| *s).collect();
        let added: Vec<i64> = e.skills.iter().copied().filter(|s| !in_db.contains(s)).collect();
        let removed: Vec<i64> = in_db.iter().copied().filter(|s| !e.skills.contains(s)).collect();
        for &s in &added {
            self.insert_link(id, s)?;
        }
        for &s in &removed {
            self.employee_skill.remove(&(id, s));
        }
        Ok((removed.len(), added.len()))
    }

    fn skills_of(&self, employee_id: i64) -> String {
        let names: Vec<&str> = self
            .employee_skill
            .iter()
            .filter(|(emp, _)| *emp == employee_id)
            .map(|(_, s)| self.skill[s].as_str())
            .collect();
        names.join(", ")
    }

    fn employees_with(&self, skill_id: i64) -> String {
        let names: Vec<&str> = self
            .employee_skill
            .iter()
            .filter(|(_, s)| *s == skill_id)
            .map(|(emp, _)| self.employee[emp].as_str())
            .collect();
        names.join(", ")
    }

    fn links(&self) -> String {
        let parts: Vec<String> = self.employee_skill.iter().map(|(e, s)| format!("{}-{}", e, s)).collect();
        parts.join(" ")
    }
}

fn main() {
    let mut db = Db {
        employee: BTreeMap::new(),
        skill: BTreeMap::from([(1, "Python".to_string()), (2, "SQL".to_string()), (3, "Go".to_string())]),
        employee_skill: BTreeSet::new(),
        last_employee: 0,
    };
    let mut ann = Employee { id: None, name: "Ann".to_string(), skills: vec![1, 2] };
    let mut bo = Employee { id: None, name: "Bo".to_string(), skills: vec![1] };
    for e in [&mut ann, &mut bo] {
        if let Err(err) = db.insert(e) {
            println!("{}", err);
        }
    }
    println!("links: {}", db.links());
    println!("Ann: {}", db.skills_of(1));
    println!("Python: {}", db.employees_with(1));

    ann.skills = vec![2, 3];
    match db.update_skills(&ann) {
        Ok((deleted, inserted)) => println!("update Ann: deleted {}, inserted {}", deleted, inserted),
        Err(err) => println!("{}", err),
    }
    println!("links: {}", db.links());
    println!("Ann: {}", db.skills_of(1));

    if let Err(err) = db.insert_link(2, 1) {
        println!("link 2-1 again: {}", err);
    }
}
Output
links: 1-1 1-2 2-1
Ann: Python, SQL
Python: Ann, Bo
update Ann: deleted 1, inserted 1
links: 1-2 1-3 2-1
Ann: SQL, Go
link 2-1 again: UNIQUE constraint failed: employee_skill.employee_id, employee_skill.skill_id
  • Verdict: idiom. The link table is a BTreeSet<(i64, i64)>, so the tuple is the key, the rows iterate in key order, and insert returns false for a pair that is already there.
  • The methods that write rows return Result, and ? passes the error of the constraint to the caller.

Consequences

Benefits.

  • Each column holds one value. The tables stay in first normal form, and both sides of the association are rows that the database can join, index and constrain.
  • One table serves both directions. The skills of an employee and the employees of a skill come from the same rows, read from the other side.
  • The database can check each link. The two foreign keys make sure that a link refers to rows that exist, and the primary key on the pair stops duplicates.
  • Frameworks make the table for the programmer. In Django, "Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship."5 In SQLAlchemy, the link table "is automatically subject to INSERT and DELETE statements, as objects are added or removed from the collection."3

Liabilities.

More queries and joins. A load of a collection needs a join with the link table, or two queries. A list of employees with their skills is a Lazy Load candidate, with the same N plus one risk as other lazy collections.

A list in a column is not a link table. A program that stores the collection as text in one column cannot use the database to find the links. In the following program, the skills are a comma-separated list, and a search for SQL also matches PostgreSQL.

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
# The skills are a list of names in one column.
db.execute("create table employee (id integer primary key, name text, skills text)")
db.execute("insert into employee (name, skills) values ('Ann', 'Python,SQL')")
db.execute("insert into employee (name, skills) values ('Bo', 'PostgreSQL')")

# Who knows SQL? A text search in the list column also matches PostgreSQL.
print(db.execute("select name from employee where skills like '%SQL%'").fetchall())
Output
[('Ann',), ('Bo',)]

Saving a changed collection. Deleting all the link rows and inserting them again is simple, but it writes many rows for a small change. Comparing the collection with the rows writes less but needs the old rows first.4 Both ways need a Unit of Work or a mapper that knows which collections changed.

Data on the link. As soon as the link itself has data, such as the date when an employee got a skill, the link table is no longer only a pair of keys. It needs a class of its own, as described in the next sections.

When not to use it

For one-to-many associations. If each skill belonged to one employee, a foreign key in the skill table would be enough. Use a Foreign Key Mapping.

When the link has its own data and behavior. Map the link table to a class of its own. SQLAlchemy calls this the association object pattern: it is "used when an association table contains additional columns beyond those which are foreign keys to the parent and child (or left and right) tables".3

For values that belong to one owner. A list of values, such as the phone numbers of one person, has no second side. Store it in a table that the owner's mapper handles, as in Dependent Mapping.

A link table with a class. Django can use a model of the program as the link table: "if you want to manually specify the intermediary table, you can use the through option to specify the Django model that represents the intermediate table that you want to use."5 Entity Framework Core calls the link table the "join entity type", and the program can map it to a class of its own, but "EF Core can hide the join entity type and manage it behind the scenes."6

A link table that is not a table. Fowler's book notes that the link table need not exist in the database: the mapper can derive links from a query on other tables, for example on a table of the events that connect the two sides.4

Foreign Key Mapping. A link table is two foreign key mappings, one to each side. Entity Framework Core says that many-to-many relationships "cannot be represented in a simple way using just a foreign key."6 See Foreign Key Mapping.

Known uses

  • Django: the ManyToManyField class in related.py at 5.2.8 is documented as "Provide a many-to-many relation by using an intermediary model that holds two ForeignKey fields pointed at the two sides of the relation."7 create_many_to_many_intermediary_model builds that model with two ForeignKey fields, on_delete=CASCADE, and unique_together on the pair.8 _add_items in related_descriptors.py inserts the link rows; the comment says "Add the ones that aren't there already."9
  • SQLAlchemy: relationship(secondary=association_table). "Many to Many adds an association table between two classes."3
  • Entity Framework Core, for .NET: a many-to-many relationship with skip navigations and a join table that has a composite primary key on the two foreign keys.6

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Association Table Mapping, pattern summary
  2. Associative entity, Wikipedia, lead section
  3. SQLAlchemy 2.0 documentation, Basic Relationship Patterns, Many To Many; Deleting Rows from the Many to Many Table; Association Object
  4. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 12, Object-Relational Structural Patterns, Association Table Mapping
  5. Django 5.2 documentation, Model field reference, ManyToManyField; Database Representation; ManyToManyField.through
  6. Entity Framework Core documentation, Many-to-many relationships, Understanding many-to-many relationships
  7. Django 5.2.8 source, django/db/models/fields/related.py, class ManyToManyField and its docstring, lines 1365 to 1374
  8. Django 5.2.8 source, django/db/models/fields/related.py, create_many_to_many_intermediary_model, lines 1308 to 1362
  9. Django 5.2.8 source, django/db/models/fields/related_descriptors.py, ManyRelatedManager._add_items, lines 1505 to 1574

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/712G7C/text.yaml