首页 > 解决方案 > Laravel 7错误外键约束在迁移过程中形成错误

问题描述

我在 Laravel 7 中迁移表时遇到问题。我正在尝试使用 belongsToMany 创建两个表的关系。产品表和图像表。我得到一个错误 150 迁移时外键约束的格式不正确。请协助。在迁移文件中:

CreateProductsTable:

Schema::create('products', function (Blueprint $table) {
             $table->id();
             $table->string('title');
             $table->string('filename');
            $table->timestamps();
        });

创建图像表

Schema::create('images', function (Blueprint $table) {
             $table->id();
             $table->string('title');
             $table->string('description');
            $table->timestamps();
        });

创建ProductsImagesTable

 Schema::create('products_images', function (Blueprint $table) {
            $table->id();
            $table->foreignId('image_id')->constrained('Images');
            $table->foreignId('product_id')->constrained('Products');
             $table->timestamps();

在模型产品

 protected $fillable = ['title','filename'];
}
public function products(){
    return $this->belongsToMany('Product','products_images'); 
}

在图像模型 {

     protected $fillable = ['title','image'];

 public function products(){
return $this->belongsToMany('Products','products_images');
}

在产品模型

 protected $fillable = ['title','filename'];

public function products(){
    return $this->belongsToMany('Images','products_images'); 
}
}

标签: laravellaravel-7

解决方案


您需要定义与表的关系,而不是类:

$table->foreignId('image_id')->constrained('images');
$table->foreignId('product_id')->constrained('products');

如果你的表名符合 Laravel 的约定,你可以忽略constrained方法的参数。所以你可以做同样的事情:

$table->foreignId('image_id')->constrained();
$table->foreignId('product_id')->constrained();

推荐阅读