Laravel 7错误外键约束在迁移过程中形成不正确

Laravel 7 error Foreign key constraint is incorrectly formed during migration

我在 Laravel 7 中迁移我的 table 时遇到问题。我正在尝试使用 belongsToMany 创建两个 table 的关系。产品 table 和图像 table。迁移时出现错误 150 Foreign key constraint is incorrectly formed。请协助。 在迁移文件中:

CreateProductsTable:

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

创建图像table

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

创建产品图像表

 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'); 
}
}

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

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

如果您的 table 名称符合 Laravel 的约定,您可以忽略 constrained 方法的参数。所以你可以用 :

做同样的事情
$table->foreignId('image_id')->constrained();
$table->foreignId('product_id')->constrained();