LALAVEL 8外键 [英] laravel 8 foreign key
本文介绍了LALAVEL 8外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试迁移具有外键的表。每次我迁移表时都会产生一个错误:
常规错误: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();
});
推荐答案
将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()方法与Constraint()一起使用
示例(摘自文档):
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});
您可以在此处了解更多详细信息:https://laravel.com/docs/8.x/migrations#foreign-key-constraints
这篇关于LALAVEL 8外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文