Skip to content

ManyToMany

Use ManyToMany when rows on both sides can have many rows on the other side.

For example, an artist has many songs, and a song has many artists.

The link is kept in a third table, the pivot table. It has one foreign key to each side.

Tables

Table Columns
artist id, name
song id, title
artist_song (pivot) id, artist_id, song_id

A migration for the pivot table:

await schema.create('artist_song', (Table table) {
  table.id();
  table.foreignId('artist_id').constrained('artist').cascadeOnDelete();
  table.foreignId('song_id').constrained('song').cascadeOnDelete();
});

Define it

Add a field with @ManyToMany(...) to each model that needs it. The field type is a list of the related model. Start it as an empty list.

lib/app/models/artist/artist.model.dart
import 'package:dox_orm/dox_orm.dart';

import '../song/song.model.dart';

part 'artist.model.g.dart';

@DoxModel()
class Artist extends ArtistGenerator {
  @Column()
  String? name;

  @ManyToMany(Song)
  List<Song> songs = <Song>[];
}
lib/app/models/song/song.model.dart
import 'package:dox_orm/dox_orm.dart';

import '../artist/artist.model.dart';

part 'song.model.g.dart';

@DoxModel()
class Song extends SongGenerator {
  @Column()
  String? title;

  @ManyToMany(Artist)
  List<Artist> artists = <Artist>[];
}

Run dart run build_runner build after you add a relationship.

Load it

The relation is not loaded by default. Load it in one of these ways. Use the field name ('songs') as the relation name.

preload

Use it when you load the models with a query.

Artist? artist = await Artist().preload('songs').find(1);
print(artist?.songs.length);

List<Song> songs = await Song().preload('artists').get();

preload works with find, get, all and getFirst. For a list of models, it runs one query for all of them. A model without links gets an empty list.

$getRelation

Use it when you already have the model.

Artist? artist = await Artist().find(1);
await artist?.$getRelation('songs');
print(artist?.songs.length);

Use it when you need more conditions on the related rows.

Artist? artist = await Artist().find(1);
List<Song> songs = await artist
        ?.related<Song>('songs')
        ?.orderBy('song.title')
        .get() ??
    <Song>[];

It does not set artist.songs. The query joins the pivot table, so write table.column for column names.

eager

Use it when every query of Artist should load the relation.

@ManyToMany(Song, eager: true)
List<Song> songs = <Song>[];

You do not call preload. Do not set eager: true on both sides. Each side would load the other side again and again.

The load runs this SQL:

SELECT "song".*, "artist_song"."artist_id" as "_owner_id" FROM "song"
  LEFT JOIN "artist_song" on "artist_song"."song_id" = "song"."id"
  WHERE "artist_song"."artist_id" IN (@artist_songartist_id_p0, ...)

Filter by it

whereHas() keeps the artists that have a song. It checks the pivot table artist_song for you. It does not load the songs.

List<Artist> artists = await Artist().whereHas('songs', (QueryBuilder<dynamic> q) {
  q.where('title', 'Yesterday');
}).get();

List<Artist> noSongs = await Artist().whereDoesntHave('songs').get();

See Query by relations.

Options

The examples are for @ManyToMany(Song) in the Artist model.

Option Default Example value What it is
pivotTable the two model names in A-Z order, joined with _ artist_song The pivot table.
pivotForeignKey {this model}_id artist_id The pivot column that points to this model.
pivotRelatedForeignKey {related model}_id song_id The pivot column that points to the related model.
localKey the primary key of this model id The column in artist that pivotForeignKey points to.
relatedKey the primary key of the related model id The column in song that pivotRelatedForeignKey points to.
onQuery none A static function that changes the query.
eager false Load the relation on every query.

The defaults use the class names in snake_case, not the table names. So @DoxModel(table: 'artists') does not change them.

  • Artist and Song give artist_song.
  • Blog and Category give blog_category.
  • BlogPost and Tag give blog_post_tag.

Set all keys

@ManyToMany(
  Song,
  pivotTable: 'artist_song',
  pivotForeignKey: 'artist_id',
  pivotRelatedForeignKey: 'song_id',
  localKey: 'id',
  relatedKey: 'id',
)
List<Song> songs = <Song>[];

onQuery

onQuery is a static function in the same model class. It gets the query of the related model and returns it.

@DoxModel()
class Artist extends ArtistGenerator {
  @ManyToMany(Song, onQuery: onlyPublished)
  List<Song> songs = <Song>[];

  static QueryBuilder<Song> onlyPublished(Song q) {
    return q.where('song.status', 'published');
  }
}

In JSON

  • A relation with eager: true is always in toJson().
  • A relation loaded with preload is in toJson() of that query.
  • The JSON key is the field name in snake_case: songs.