首页 > 解决方案 > 在 Laravel 7 中导入表 daa 的迁移命令

问题描述

通过使用迁移,我可以导入 Laravel 网站的数据库结构。但是,导入其数据的最佳和正确方法是什么。

迁移中是否有可用的命令?

需要帮忙。我正在使用 Laravel 7。

谢谢

标签: laravellaravel-7laravel-artisan

解决方案


当您必须将表及其数据迁移到其他项目(如 Laravel)时,此问题很常见。

建议的解决方案

  1. 将要迁移的表的数据转储到.sql文件中,并将该文件放在文件夹中您可以访问它的某个位置。为方便起见,请将文件放在public文件夹中。

  2. 发出命令以导入该.sql文件。

  3. 制作播种机并在run function.

实施指南

发出命令

php artisan make:command ImportXTable

该命令将在 app/Console/Commands 目录中创建一个新的命令类。

生成命令后,转到app/Console/Commands目录并打开刚刚创建的文件即 ImportXTable,您应该填写类的签名和描述属性,这些属性将在列表屏幕上显示您的命令时使用。执行命令时将调用句柄方法。您可以将命令逻辑放在此方法中。

示例脚本

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ImportXTable extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:xtable';//this is what you will call  to import table

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import the .sql file for ImportXTable';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $sql = public_path('fileNameToImport.sql');// write the sql filename here to import
        
        
        DB::unprepared(file_get_contents($sql));
    }
}

然后在kernel.php数组中commands注册您的命令,如下所示

  protected $commands = [
        Commands\ImportXTable::class,
    ];

播种机实施

为 Xtable 制作一个播种机并在播种机中调用该命令,如下所示

<?php

use Illuminate\Database\Seeder;

class XTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        \Artisan::call('import:xtable');//calling the command to import data from .sql file to database table
    }
}

现在,当您运行播种机时,文件将从转储 sql 导入到您的表中。

请记住配置您的 sql 文件以导入所需的表并保持表名相同,或者您可以在编辑器中编辑 .sql 文件

例如你可以编辑你的 Sql 文件并写这个

insert  into `x_table`(`column_name1`,`column_name2`,`column_name3`) values 

(0,16777215,'-','-'),
............

推荐阅读