ManyToMany
A "many-to-many" relationship is a powerful concept in database design, often used to represent complex associations between entities. Consider a scenario where we have an Artist model and a Song model. To represent the fact that each artist can have multiple songs, and each song can have multiple artists, we establish a "many-to-many" relationship.
To achieve this, we typically create an intermediary table, often referred to as a "pivot" or "junction" table, which contains foreign keys referencing both the Artist and Song models. This table captures the relationships between artists and songs.
class ManyToMany {
final Type model;
final Function? onQuery;
final bool? eager;
final String? localKey;
final String? relatedKey;
final String? pivotForeignKey;
final String? pivotRelatedForeignKey;
final String? pivotTable;
const ManyToMany(
this.model, {
this.eager,
this.onQuery,
this.localKey,
this.relatedKey,
this.pivotForeignKey,
this.pivotRelatedForeignKey,
this.pivotTable,
});
}
Usage
$getRelation
Info
When eager is true the $getRelation do not need to call.
preload
Info
When eager is true the preload do not need to call.
related
Options
model
localKey
Model primary key.
relatedKey
Related model primary key.
pivotForeignKey
Info
If model is Artist, artist_id from pivot table. If model is Song, song_id from pivot table.
pivotRelatedForeignKey
Info
If model is artist, song_id from pivot table. If model is song, artist_id from pivot table.
pivotTable
Info
By default, the pivot table will be named alphabetically, as demonstrated by these examples:
- For tables named
songandartist, the pivot table would be namedartist_song. - In the case of tables named
blogandcategory, the default pivot table name would beblog_category.
However, you have the flexibility to provide a custom name to the pivotTable parameter if needed.
onQuery
Info
onQuery method must be a static method inside the model.