我需要为我的数据库使用外键但我不能这样做,在命令行中运行migration命令后,我收到此错误:
[Illuminate\Database\QueryException] SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL:alter table
samples
add constraint s amples_supplier_id_foreign foreign key(supplier_id
)referencessuppliers
(id
))[PDOException] SQLSTATE [HY000]:常规错误:1215无法添加外键约束
样本迁移:
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,但再次失败
订单很重要.
在尝试引用该表上的列作为约束之前,您需要确保"供应商"表存在.
因此,如果要在创建表时设置外键约束,请确保先创建" 供应商 "迁移,然后再创建" 样本 "迁移:
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