Brak opisu

DatabaseSeeder.php 2.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. class DatabaseSeeder extends Seeder {
  3. /**
  4. * Run the database seeds.
  5. *
  6. * @return void
  7. */
  8. public function run()
  9. {
  10. Eloquent::unguard();
  11. // IMPORTANT: Do not change order without understanding DB structure and each class first
  12. $this->call('UserTableSSNDecrypter'); // Decrypt employees' SSNs
  13. $this->call('UserTableSeeder'); // Update existing employees and add new employees
  14. $this->call('CourseTableSeeder'); // Add/update courses
  15. $this->call('UserTableSSNEncrypter'); // Encrypt employees' SSNs
  16. $this->call('StudentTableSeeder'); // Add/update students
  17. $this->call('CourseStudentTableSeeder'); // Add/update course-student enrollment (matrícula)
  18. // Step 2 :New seeders to add programs to programs_user table
  19. // $this->call('ProgramUserTableSeeder'); // Adds new lines to programs_users table using programs_users.csv file (Refer to OLAS guide for usage)
  20. }
  21. /**
  22. * Seeds a table by reading from a csv file
  23. *
  24. * Example: $this->insertFromCSV('courses', 'courses.csv');
  25. *
  26. * @param string $table Name of the table to be seeded
  27. * @param string $filename Name and extension of the file
  28. *
  29. * @var resource $file Pointer to CSV file to get imported
  30. * @var array $columns Array with column names for the table
  31. * @var int $rowIndex Index of row number
  32. * @var array $dbArray Array to be inserted into the database
  33. * @var int $columnIndex Index of column number
  34. *
  35. * @return void
  36. */
  37. public function insertFromCSV($table, $filename)
  38. {
  39. // Disable foreign key checks before truncating
  40. DB::statement('SET FOREIGN_KEY_CHECKS=0;');
  41. // Truncate table
  42. DB::table($table)->truncate();
  43. // Enable foreign key checks
  44. DB::statement('SET FOREIGN_KEY_CHECKS=1;');
  45. // Get columns
  46. $file = fopen('app/database/csv/'.$filename, 'r');
  47. $columns = fgetcsv($file, 5000, ",");
  48. /** Initialize row index to 0 */
  49. $rowIndex = 0;
  50. /** Initialize empty array */
  51. $dbArray=array();
  52. /** Read each row */
  53. while($data = fgetcsv($file, 5000, ","))
  54. {
  55. /** Initialize column index */
  56. $columnIndex = 0;
  57. /** For each column within a row, assign column name and value */
  58. foreach($data as $value)
  59. {
  60. $dbArray[$rowIndex][$columns[$columnIndex]] = $value;
  61. $columnIndex++;
  62. }
  63. $rowIndex++;
  64. }
  65. DB::table($table)->insert($dbArray);
  66. }
  67. }