laravel - 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');
}
}
解决方案
您需要定义与表的关系,而不是类:
$table->foreignId('image_id')->constrained('images');
$table->foreignId('product_id')->constrained('products');
如果你的表名符合 Laravel 的约定,你可以忽略constrained
方法的参数。所以你可以做同样的事情:
$table->foreignId('image_id')->constrained();
$table->foreignId('product_id')->constrained();
推荐阅读
- javascript - 无法在 JavaScript 中导入 AlertifyJS
- indexing - Julia - 以元组数组作为索引的 JuMP 约束
- ios - 通过蓝牙将媒体密钥发送到 iOS 设备
- python - 做一个 groupby 和一个 sum 但在 Pandas DataFrame 中保持其他列完整
- javascript - 如何按比例缩放组件/页面,如 Ctrl +/-
- qt - 如何使 QAbstractSpinBox 自动重复向上/向下按钮?
- javascript - 无法将变量设置为 Bcrypt 生成的哈希
- python - 如何避免使用 Autoreg 或 ARIMA Statsmodels 进行动态预测
- c# - 未捕获任务错误
- ios - 在 iOS 15 中未分配 Alamofire 4.9.1 sessionManager.delegate.sessionDidReceiveChallenge