随着项目规模的扩大,我们决定每个数据都应该属于创建这些数据的公司。因此,我将添加一个列"data_owner_company_id“,指向拥有给定记录的公司。是的,向每个模型添加这一列是可以生成迁移的,但是这并不是完全可行的,因为有120+表和模型。,我如何用最小的努力来解决这个问题呢?
对于模型部分,我想我可以很容易地通过继承将它应用到所有模型,但对于迁移并不确定。
如何通过迁移将int列添加到所有表中?
数据库: MySQL v8框架: Laravel 8,PHP7.3
发布于 2021-06-29 12:34:36
如果您在数据库中找到所有表的名称,这很简单,您必须循环并为每个表创建列。
尝试使用队列创建列,因为对120个表来说这将是一项繁重的工作。
检查以下代码:
class CreateDataOwnerCompanyIdtoEachTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up ()
{
$columns = 'Tables_in_' . env('DB_DATABASE');//This is just to read the object by its key, DB_DATABASE is database name.
$tables = DB::select('SHOW TABLES');
foreach ( $tables as $table ) {
//todo add it to laravel jobs, process it will queue as it will take time.
Schema::table($table->$columns, function (Blueprint $table) {
$table->unsignedInteger('data_owner_company_id');
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down ()
{
$columns = 'Tables_in_' . env('DB_DATABASE');//This is just to read the object by its key, DB_DATABASE is database name.
$tables = DB::select('SHOW TABLES');
foreach ( $tables as $table ) {
//todo add it to laravel jobs, process it will queue as it will take time.
Schema::table($table->$columns, function (Blueprint $table) {
$table->dropColumn('data_owner_company_id');
});
}
}
}发布于 2021-06-29 12:16:40
我不能百分之百肯定它会起作用,但我现在说:
创建扩展Illuminate\Database\Schema\Blueprint;的类
在构造函数中调用父构造器,然后
$this->unsignedBigInteger('data_owner_company_id')->nullable();在迁移中使用新类而不是默认的Blueprint
https://stackoverflow.com/questions/68178047
复制相似问题