The many-to-many example provided with the introduction of Mirage 0.3 lays out how to create many-to-many joins between specific instances of two models. It does this by hard coding the creation of a few books and a couple of authors, as well as the links between them, but stops short of using factories to generate such relationships on demand.
Using that example as a very useful starting point, I updated it to include factories and random joins between the two models. The interesting code happens in the default scenario, where two independent sets are generated―one of authors, one of books―and then each book is randomly assigned between one and three of the authors. (A side effect of this approach is that it is possible to end up with authors on the list that have zero books associated with them.)
Given a function randomSubset to select a random subset of the given array, the fundamental setup is straightforward:
1 2 3 4 5 6 7 8 9 |
let authors = server.createList('author', 6) let books = server.createList('book', 5) books.forEach((book) => { let numAuthors = faker.random.number({min: 1, max: 3}) let authorsOfBook = randomSubset(authors, numAuthors) book.authors = authorsOfBook book.save() }); |
Alternatively, if instead of using the author model instances you have a random subset of the author ids, the same result can be achieved simply by setting book.authorIds to that array of integers instead.
David
Great guide. I was scratching my head about how to succinctly create many-to-many relationships using Mirage factories, and I couldn’t find anything decent while sifting through the documentation. This is exactly what I needed. Cheers!