我试图迁移有外键的桌子。每次迁移表时,都会产生一个错误,即:
一般错误: 1215无法添加外键约束
下面是我的表迁移:
Schema::create('profile_pictures', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->nullable();
$table->binary('image')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});这是我的模型:
class ProfilePicture extends Model
{
protected $fillable = [
'user_id',
'image'
];
public function user()
{
$this->belongsTo(User::class, 'user_id', 'id');
}
}下面是我的用户表迁移:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('username');
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('email')->unique();
$table->string('phone')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});发布于 2021-02-22 05:03:13
将user_id从bigInteger更新为UnsignedBigInteger,因为PK和FK需要相同的数据类型和长度。
Schema::create('profile_pictures', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->binary('image')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});我将建议遵循约定,并使用带约束()的foreignId()方法
样本(来自文件):
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});您可以在这里获得更多详细信息:https://laravel.com/docs/8.x/migrations#foreign-key-constraints
发布于 2021-02-22 04:09:25
根据WL#148,外键列必须具有与相应的引用列相同的数据类型+相同的长度+相同的比例尺。
我觉得你应该用
$table->unsignedBigInteger('user_id')->nullable(); 而不是
$table->bigInteger('user_id')->nullable();https://stackoverflow.com/questions/66309431
复制相似问题