[英]error while migrating with foreign key in laravel
我試圖在函數下面遷移,但它每次都給我同樣的錯誤,我沒能找出原因,即使我嘗試了文檔中的其他語法
//向上函數
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id('cat_id');
$table->string('cat_name');
$table->string('cat_desc');
$table->string('cat_image');
$table->timestamps();
});
Schema::create('sellers', function (Blueprint $table) {
$table->id('seller_id');
$table->string('seller_name');
$table->string('seller_desc');
$table->string('seller_image');
$table->timestamps();
});
Schema::create('products', function (Blueprint $table) {
$table->id('prd_id');
$table->string('prd_name');
$table->string('prd_price');
$table->string('prd_image');
$table->string('prd_desc');
$table->foreignId('product_cat_id')->constrained('categories');
$table->foreignId('product_seller_id')->constrained('sellers');
$table->boolean('prd_status');
$table->timestamps();
});
}
//錯誤
SQLSTATE[HY000]: General error: 1005 Can't create table ecommerce.products (errno: 150 "Foreign key constraint is wronglyformed") (SQL: alter table products add constraint products_product_cat_id_foreign外鍵(product_cat_id)引用類別(id))
我還從數據庫中刪除了遷移文件並進行了新的遷移,但沒有幫助,請指導我,在此先感謝
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->integer('cat_id')->unsigned();
$table->string('cat_name');
$table->string('cat_desc');
$table->string('cat_image');
$table->timestamps();
});
Schema::create('sellers', function (Blueprint $table) {
$table->increments('id');
$table->integer('seller_id')->unsigned();
$table->string('seller_name');
$table->string('seller_desc');
$table->string('seller_image');
$table->timestamps();
});
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('prd_id')->unsigned();
$table->string('prd_name');
$table->string('prd_price');
$table->string('prd_image');
$table->string('prd_desc');
$table->foreignId('product_cat_id')->constrained('categories');
$table->foreignId('product_seller_id')->constrained('sellers');
$table->boolean('prd_status');
$table->timestamps();
});
}
這是因為,在您的categories
和sellers
,表主鍵都不是id
,默認情況下受約束的方法使用id
作為主鍵作為外鍵引用,因此更改:
$table->foreignId('product_cat_id')->constrained('categories');
$table->foreignId('product_seller_id')->constrained('sellers');
到,
$table->unsignedBigInteger('product_cat_id');
$table->foreign('product_cat_id')->references('cat_id')->on('categories');
$table->unsignedBigInteger('product_seller_id');
$table->foreign('product_seller_id')->references('seller_id')->on('sellers');
如果您使用的是模型,那么還要在模型上定義主鍵,例如:
protected $primaryKey = 'cat_id';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.