Laravel framework uses Seeder to realize automatic data filling function

  • 2021-10-16 01:16:32
  • OfStack

In this paper, the Laravel framework uses Seeder to realize the function of automatically filling data. Share it for your reference, as follows:

To view the code, click the link: https://github.com/laravel/framework

The Laravel auto-populate data uses the Seeder class


<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
  /**
   * Run the database seeds.
   */
  public function run()
  {
    //
  }
}
class MyTableSeeder extends Seeder
{
  public function run()
  {
    //
  }
}

Your custom Seeder has only one run function, which writes your auto-fill steps

You will notice that these two functions


Model::unguard();
// Your fill operation 
Model::reguard();

Once, I was very confused about these two functions. What are they used for? I can only speculate that they are a pair of functions that react to each other. So I checked the source code.

These two functions are defined under Model. php under the directory\ vendor\ laravel\ framework\ src\ Illuminate\ Database\ Eloquent


/**
* Disable all mass assignable restrictions.
*
* @param bool $state
* @return void
*/
public static function unguard($state = true)
{
    static::$unguarded = $state;
}
/**
* Enable the mass assignment restrictions.
*
* @return void
*/
public static function reguard()
{
    static::$unguarded = false;
}

As you can see from the comments of Laravel author, it is an operation of data filling restriction.

Therefore, unguard comes first, reguard comes second, unguard is responsible for lifting the automatic fill operation restriction, and reguard is responsible for restoring the restriction.

It is recommended to use the member functions of the model before populating operations


Model::truncate();

This function will empty the data table corresponding to this model, so please use it carefully.


<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
  /**
   * Run the database seeds.
   */
  public function run()
  {
    Model::unguard();
    $this->call('PostTableSeeder');
    Model::reguard();
  }
}
class PostTableSeeder extends Seeder
{
  public function run()
  {
    App\Post::truncate();
    factory(App\Post::class, 1000)->create();
  }
}

Some readers here will ask: Why don't we write all the fill operations in the run function of our own DatabaseSeeder?

Because we develop a complete system, there are many data tables that may need to be populated, so we don't want to modify this run function in large quantities every time. We also want to keep this filling process for every filling, so we'd rather write a new class and use $this- > call () function.

Next, let's talk about factory.

File directory\ database\ factories\ ModelFactory. php


$factory->define(App\Post::class, function ($faker) {
  return [
    'title' => $faker->sentence(mt_rand(3, 10)),
    'content' => join("\n\n", $faker->paragraphs(mt_rand(3, 6))),
    'published_at' => $faker->dateTimeBetween('-1 month', '+3 days'),
  ];
});

Although I can understand it, I don't know what this $factory variable is. So look for Factory class.

Find the source code in the directory\ vendor\ laravel\ framework\ src\ Illuminate\ Database\ Eloquent Factory. php


/**
* Define a class with a given set of attributes.
*
* @param string $class
* @param callable $attributes
* @param string $name
* @return void
*/
public function define($class, callable $attributes, $name = 'default')
{
    $this->definitions[$class][$name] = $attributes;
}


/**
* Create an instance of the given model and persist it to the database.
*
* @param string $class
* @param array $attributes
* @return mixed
*/
public function create($class, array $attributes = [])
{
    return $this->of($class)->create($attributes);
}

To start populating the data, let's still use the artisan command line


php artisan db:seed

This command will execute the run function of all the classes you write in DatabaseSeeder. php. If the project is complicated in the future, it is not necessary to execute what has already been executed, so add parameters behind the command line, as long as you execute the run function of a certain class.


php artisan db:seed --class= The name of the class you want to execute 

More readers interested in Laravel can check the topics of this site: "Introduction and Advanced Tutorial of Laravel Framework", "Summary of Excellent Development Framework of php", "Introduction Tutorial of php Object-Oriented Programming", "Introduction Tutorial of php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

Hope that this article is based on Laravel framework of PHP programming help.


Related articles: