laravel - 在 Laravel 7 中导入表 daa 的迁移命令
问题描述
通过使用迁移,我可以导入 Laravel 网站的数据库结构。但是,导入其数据的最佳和正确方法是什么。
迁移中是否有可用的命令?
需要帮忙。我正在使用 Laravel 7。
谢谢
解决方案
当您必须将表及其数据迁移到其他项目(如 Laravel)时,此问题很常见。
建议的解决方案
将要迁移的表的数据转储到
.sql
文件中,并将该文件放在文件夹中您可以访问它的某个位置。为方便起见,请将文件放在public
文件夹中。发出命令以导入该
.sql
文件。制作播种机并在
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,'-','-'),
............
推荐阅读
- typescript - 离线后并非所有通知都显示
- java - 在 maven 项目中使用 jstl 从 MySQL 数据库中获取数据时出错
- assembly - 新组装,旨在打印 '0' 到 '9' ,意外错误
- c# - AutoMapper 全局前缀/后缀
- c# - 检测 C# 应用程序何时进入睡眠状态(未调用 SystemEvents.PowerModeChanged)
- c# - 当我输入条目时,轮播视图将我滚动到第一个项目
- python - 如何解决 403 错误抑制 Google Cloud Dataflow 可以启动的工作人员数量?
- laravel - 如何计算 Laravel 中分组集合中的项目数?
- python - 从保存的 Keras 模型获取 tf.Serving 的配置
- database - 如何使用 gremlin 将所有顶点连接到组中的至少两个其他顶点?