SeedCommand.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace Illuminate\Database\Console\Seeds;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Console\ConfirmableTrait;
  6. use Symfony\Component\Console\Input\InputOption;
  7. use Illuminate\Database\ConnectionResolverInterface as Resolver;
  8. class SeedCommand extends Command
  9. {
  10. use ConfirmableTrait;
  11. /**
  12. * The console command name.
  13. *
  14. * @var string
  15. */
  16. protected $name = 'db:seed';
  17. /**
  18. * The console command description.
  19. *
  20. * @var string
  21. */
  22. protected $description = 'Seed the database with records';
  23. /**
  24. * The connection resolver instance.
  25. *
  26. * @var \Illuminate\Database\ConnectionResolverInterface
  27. */
  28. protected $resolver;
  29. /**
  30. * Create a new database seed command instance.
  31. *
  32. * @param \Illuminate\Database\ConnectionResolverInterface $resolver
  33. * @return void
  34. */
  35. public function __construct(Resolver $resolver)
  36. {
  37. parent::__construct();
  38. $this->resolver = $resolver;
  39. }
  40. /**
  41. * Execute the console command.
  42. *
  43. * @return void
  44. */
  45. public function handle()
  46. {
  47. if (! $this->confirmToProceed()) {
  48. return;
  49. }
  50. $this->resolver->setDefaultConnection($this->getDatabase());
  51. Model::unguarded(function () {
  52. $this->getSeeder()->__invoke();
  53. });
  54. }
  55. /**
  56. * Get a seeder instance from the container.
  57. *
  58. * @return \Illuminate\Database\Seeder
  59. */
  60. protected function getSeeder()
  61. {
  62. $class = $this->laravel->make($this->input->getOption('class'));
  63. return $class->setContainer($this->laravel)->setCommand($this);
  64. }
  65. /**
  66. * Get the name of the database connection to use.
  67. *
  68. * @return string
  69. */
  70. protected function getDatabase()
  71. {
  72. $database = $this->input->getOption('database');
  73. return $database ?: $this->laravel['config']['database.default'];
  74. }
  75. /**
  76. * Get the console command options.
  77. *
  78. * @return array
  79. */
  80. protected function getOptions()
  81. {
  82. return [
  83. ['class', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder', 'DatabaseSeeder'],
  84. ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to seed'],
  85. ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'],
  86. ];
  87. }
  88. }