How to Seed a Multiple Field Type in a PyroCMS Module

I've recently been building a variety of PyroCMS modules. And because I work for a university, these modules are mostly oriented toward managing data you'd find associated with a higher education website: degrees, academic news, events, areas of academic study, etc. In my latest module, I was trying to seed a database of academic disciplines (art, business, biology, etc.) and associate entries in a "degrees" table with each academic discipline. This would mean, for example, that the biology discipline would have many biology degrees.

Along the way, I ran into trouble trying to seed the database of disciplines. I couldn't quite figure out how the 'multiple field type' could be seeded. So I tossed a question into the PyroCMS Slack channel.

belongsToMany.jpg

Ryan Thompson (the big big kahuna behind PyroCMS) pointed out that the multiple field type is just a native Laravel belongsToMany relationship. With that in mind, it was easy to see that I could use the sync method to construct many-to-many associations. "The sync method accepts an array of IDs to place on the intermediate table" when joining data through a pivot table (Otwell, 2018). Check out the example below.

In this example, you can see that I've created an array of academic disciplines. Within each discipline in the array, I've listed product_ids, which are the IDs of degrees I have in a table called 'products'. My seeder's run method loops over the array of disciplines, creates a new database entry for each discipline, and then creates the relationship over the pivot table with the sync method.

One clear upgrade you could make to this seeder would be to dynamically collect the product_ids using another method. I decided not to demonstrate that here so that the fundamental concept could be easily seen.

Good luck seeding your next PyroCMS module.


Otwell, Taylor. “Eloquent: Relationships” laravel.com. https://laravel.com/docs/5.5/eloquent-relationships#many-to-many (accessed March 7, 2018).