Database / ORM Overview
Seeding & Pivot Tables
When working with complicated many-to-many associations in relational databases, an intermediary "Pivot Table" is required to map siblings together. Archery handles this beautifully using a specialized PivotTable migration pattern.
Defining a Pivot Table
To bridge two distinct models through a belongsToMany relationship, define a class that extends PivotTable<T, U>.
Inside that class, declare the two foreign keys required to stitch identical IDs from both target models together:
class UserRolePivot extends PivotTable<User, Role> {
@override
late final Map<String, String> columnDefinitions = {
'user_id': 'INTEGER NOT NULL',
'role_id': 'INTEGER NOT NULL',
};
}
By default, every Archery PivotTable includes standard internal id, created_at, and updated_at properties automatically.
Migrating Pivots
Once you've established the parameters holding your two models tightly together, simply instruct Archery to migrate this pivot table inside one of your Application Providers during the boot sequence:
final pivot = UserRolePivot();
// Pass the target database driver
await pivot.migrate(disk: DatabaseDisk.sqlite);
When evaluated, Archery will automatically construct compound relationship indices and strict unique indices to ensure lightning-fast subsequent fetches.
Seeding Relational Data
With migrations complete, executing Database Seeds to populate relationships is effortlessly dynamic. Archery's ORM mutators handle the pivot entries implicitly during programmatic execution.
Simply instantiate your models and use the attach mutator to bridge them:
final adminUser = User(name: "Administrator")..save();
final superRole = Role(slug: "superuser")..save();
final pivot = UserRolePivot();
// Seed the tables safely automatically!
await adminUser.attach(
superRole,
relationship: ModelRelationshipType.belongsToMany,
table: pivot,
disk: DatabaseDisk.sqlite
);