Database Seeding
Formidable includes the ability to seed your database with data using Knex.js seeders. All seeders are stored in the database/seeders
directory.
Writing Seeders
To generate a seeder, execute the make:seed
Craftsman command. All seeders generated by the framework will be placed in the database/seeders
directory:
node craftsman make:seed Users --table="users"
A seeder contains one export by default: seed
. This export returns an anonymous function which is called when the db:seed
Craftsman command is executed. Within the function, you may insert data into your database however you wish. You may use the Knex.js query builder to manually insert data.
Here's an example of a users
seeder that deletes all the users before adding a new one:
const { Database, Hash } = require('@formidablejs/framework');
const { strRandom } = require('@formidablejs/framework/lib/Support/Helpers');
/** @param {Database} DB */
exports.seed = function (DB) {
// Deletes ALL existing entries
return DB.table('users').del()
.then(async function () {
const password = await Hash.make('password');
// Inserts seed entries
return DB.table('users').insert([
{
name: strRandom(10),
email: strRandom(10) + '@gmail.com',
password: password,
},
]);
});
};
Running Seeders
You may execute the db:seed
Craftsman command to seed your database. This command will run all your seeders:
node craftsman db:seed