laravel - 如何创建一个可以调用所有迁移类的主迁移类?
问题描述
在 Laravel 中,创建迁移和播种器的顺序是必不可少的。
当这些在 artisan 中运行时,如果一个类(表)中有任何外键,并且一个在被引用的那个之前执行,那么执行将停止,并且你会得到一个错误。
DatabaseSeeder
当您调用 php artisan 时,会运行一个名为的类db:seed
。本课程包括您所有的播种机课程。
https://laravel.com/docs/5.7/seeding#writing-seeders
迁移是否有任何等价物?
<?php
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call([
LanguageTableDataSeeder::class,
UserTableDataSeeder::class,
PlaceTableDataSeeder::class]);
}
}
解决方案
是的,你可以做到
但不推荐
第 1 步:运行命令 phpartisan make:migration create_bulk_table
现在打开你的迁移文件夹,database/migrations
你会发现新的迁移time_stamp_create_bulk_table.php
打开它你会发现这样的内容
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBulkTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('bulk', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('bulk');
}
}
怎么做
这里面有两种方法
一个是因为creating the table
那是up METHOD
和
另一个是dropping the table
因为down METHOD
例如,如果您想迁移
posts
表,tasks
表,products
表
在单一迁移中
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBulkTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (!Schema::hasTable('posts'))
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('post_name');
$table->text('post_desc');
$table->timestamps();
});
}
if (!Schema::hasTable('tasks'))
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->string('task_name');
$table->enum('task_status', ['Open', 'Closed','Inactive']);
$table->text('task_desc');
$table->timestamps();
});
}
if (!Schema::hasTable('products'))
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('product_name');
$table->text('product_desc');
$table->string('product_price');
$table->timestamps();
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
Schema::dropIfExists('tasks');
Schema::dropIfExists('products');
}
}
BE CAREFUL WHILE REFERING THE FORIEGN KEY OF PARENT TABLE WHICK NEEDS TO BE CREATED BEFORE THE REFERAL
例如,您user_id
在帖子表中有列,您所指的是
$table->foreign('user_id')->references('id')->on('users');
users
table 需要在posts
table之前迁移
希望清楚
如果您发现任何错误,请在下方评论
推荐阅读
- pandas - pandas_profiling 运行时间过长
- kubernetes - 如何在没有云提供商或 LB 的情况下获取 pod 内的客户端 ip
- javascript - 按下按钮后使用javascript打开表单
- firefox - 如何在firefox上使用javascript转换功能画中画
- java - 即使在 HotSpot 中没有带有 CMS 的 Full GC 的情况下,Old Generation 的大小如何减小?
- solr - 如何在 Hybris 的 Solr 更新中跳过坏文档
- grafana - InfluxDB 时间落后 15 分钟
- sql - 如何在Oracle中按日期分组和排序?
- c - 为什么我得到 SIGABRT?
- amazon-web-services - 清理 AWS CodePipeline 中的旧文件