Database
Database: seeding
Seeders fill your database with data, such as a first user for your own machine or the rows your tests and demos need.
Introduction#
A seeder is a class in database/ with a run() method. A new app has one, DatabaseSeeder, which db:seed
runs unless you name another. It creates a test user; add a this.call() for each seeder you write.
Seeders run with mass assignment protection off, so create() takes every attribute you give it.
Writing seeders#
make:seeder writes a seeder in database/:
node oriel make:seeder UserSeederA seeder's run() can insert rows with the query builder, or create models with their
factories. It is async, so await each insert:
import { DB, Hash, Seeder, Str } from '@orieljs/framework'export default class UserSeeder extends Seeder { /** Run the database seeders. */ async run(): Promise<void> { await DB.table('users').insert({ name: Str.random(10), email: `${Str.random(10)}@example.com`, password: await Hash.make('password'), }) }}The file's default export is the seeder, or its export named after the file.
Using model factories#
Factories make many rows at once, with realistic values. A new app's DatabaseSeeder uses the User factory:
import { Seeder } from '@orieljs/framework'import { User } from '../../app/Models/User'export default class DatabaseSeeder extends Seeder { async run(): Promise<void> { await User.factory().create({ name: 'Test User', email: 'test@example.com', }) }}User.factory(50).create() makes 50 users. Factories shows how to write factories and give
them related models.
Calling additional seeders#
call() runs other seeders, in order, and prints each one's name as it runs:
import { Seeder } from '@orieljs/framework'import PostSeeder from './PostSeeder'import UserSeeder from './UserSeeder'export default class DatabaseSeeder extends Seeder { async run(): Promise<void> { await this.call(UserSeeder, PostSeeder) }}callSilent() runs them without printing.
Running seeders#
db:seed runs DatabaseSeeder. Name another seeder to run it alone:
node oriel db:seednode oriel db:seed UserSeeder--database runs the seeder on another connection, which becomes the default while it runs.
--seed runs DatabaseSeeder after migrate, migrate:fresh or migrate:refresh, and --seeder another one:
node oriel migrate:fresh --seednode oriel migrate:fresh --seed --seeder=UserSeederForcing seeders to run in production#
In production, db:seed stops unless you pass --force, so you can't fill your live database with test data by
mistake:
node oriel db:seed --force