我需要为我的数据库使用外键,但我不能这样做,在命令行中运行迁移命令后,我收到此错误:
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
samples
add constraint s amples_supplier_id_foreign foreign key (supplier_id
) referencessuppliers
(id
))[PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
样本迁移:
Schema::create('samples', function (Blueprint $table) {
$table->Increments('id',true);
$table->string('variety',50);
$table->integer('supplier_id')->unsigned();
$table->foreign('supplier_id')->references('id')->on('suppliers');
$table->string('lot_number');
$table->date('date');
$table->integer('amount');
$table->integer('unit_id')->unsigned();
$table->foreign('unit_id')->references('id')->on('unit');
$table->string('technical_fact');
$table->string('comments');
$table->string('file_address');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('category');
$table->timestamps();
});
供应商迁移:
Schema::create('suppliers', function (Blueprint $table) {
$table->Increments('id',true);
$table->string('supplier',50);
$table->timestamps();
});
我尝试通过新的样本迁移来实现这一点,但没有成功:
Schema::create('samples', function (Blueprint $table) {
$table->Increments('id',true);
$table->string('variety',50);
$table->integer('supplier_id')->unsigned();
$table->string('lot_number');
$table->date('date');
$table->integer('amount');
$table->integer('unit_id')->unsigned();
$table->string('technical_fact');
$table->string('comments');
$table->string('file_address');
$table->integer('category_id')->unsigned();
$table->timestamps();
});
Schema::table('samples', function($table) {
$table->foreign('supplier_id')->references('id')->on('suppliers');
$table->foreign('unit_id')->references('id')->on('unit');
$table->foreign('category_id')->references('id')->on('category');
});
我尝试将主键的长度固定为10,但再次失败
最佳答案
订单很重要。
在尝试引用该表上的列作为约束之前,您需要确保您的“供应商”表存在。
因此,如果您想在创建表时设置外键约束,请确保先创建“suppliers”迁移,然后再创建“samples”迁移之后:
php artisan make:migration create_suppliers_table --create=suppliers
php artisan make:migration create_samples_table --create=samples
...将模式代码添加到您的迁移文件中。然后:
php artisan migrate
如果您不想担心表的创建顺序,那么首先执行您的 create_table 迁移,没有外键约束,然后执行额外的迁移以添加您的外键。
php artisan make:migration create_samples_table --create=samples
php artisan make:migration create_suppliers_table --create=suppliers
php artisan make:migration alter_samples_table --table=samples <-- add your foreign key constraints to this migration file
...将模式代码添加到您的迁移文件中。然后迁移使用:
php artisan migrate
关于php - 如何在 Laravel 5.1 迁移中使用外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34117302/