ExportCommand.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Exceptions\ClientException;
  4. use App\Import\CategoryImport;
  5. use App\Models\Goods\Category;
  6. use Illuminate\Console\Command;
  7. use Illuminate\Support\Facades\DB;
  8. use Maatwebsite\Excel\Facades\Excel;
  9. class ExportCommand extends Command
  10. {
  11. /**
  12. * The name and signature of the console command.
  13. *
  14. * @var string
  15. */
  16. protected $signature = 'export {cmd?}';
  17. /**
  18. * The console command description.
  19. *
  20. * @var string
  21. */
  22. protected $description = 'Command description';
  23. public function handle()
  24. {
  25. $cmd = $this->argument('cmd');
  26. $args = $this->arguments();
  27. unset($args['command'], $args['cmd']);
  28. $params = array_values($args);
  29. if (empty($cmd)) {
  30. echo 'Nothing to do...';
  31. } else {
  32. if (method_exists($this, $cmd)) {
  33. call_user_func_array([$this, $cmd], $params);
  34. } else {
  35. echo 'cmd not exists';
  36. }
  37. }
  38. return;
  39. }
  40. public function category()
  41. {
  42. //从一个表格中获取数据,并放入到一个数组中
  43. $r = (new CategoryImport())->collection(Excel::toCollection(null, storage_path('app/public/category.xls'))[0]);
  44. DB::transaction(function () use ($r) {
  45. foreach ($r as $k => $v) {
  46. if ($k == 0) {
  47. continue;
  48. }
  49. /** @var Category $category */
  50. $category = Category::where("name", $v[1])->first();
  51. $data = [
  52. 'name' => $v[0],
  53. 'parent_id' => optional($category)->id ?? 0,
  54. 'level' => optional($category)->level + 1,
  55. 'thumb' => "https://iph.href.lu/400x200",
  56. 'weight' => $v[2],
  57. 'index_weight' => $v[3],
  58. "category_weight" => $v[5],
  59. "search_weight" => $v[4],
  60. ];
  61. $c = new Category($data);
  62. $c->save();
  63. }
  64. });
  65. }
  66. }