【发布时间】:2021-08-18 04:17:47
【问题描述】:
SQLSTATE[HY000]:一般错误:1005 无法创建表
laravel.projects(errno: 150 "外键约束为 格式不正确")
当我迁移我的项目表并尝试加入三个表时出现上述错误:
- 一个用户有很多产品,产品有自己的ID。
- 一个产品有很多项目,项目有自己的id。
用户表(user.php)
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->text('profile_photo_path')->nullable();
$table->timestamps();
});
}
产品表(product.php)
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('detail');
$table->string('color');
$table->string('image');
$table->string('logo');
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
项目表(project.php)
Schema::create('projects', function (Blueprint $table) {
// $table->('id');
$table->bigIncrements('id');
$table->string('name', 255)->nullable();
$table->string('detail', 500)->nullable();
$table->string('color', 255)->nullable();
$table->string('image', 22)->nullable();
$table->string('logo', 22)->nullable();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('product_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable();
});
用户模型
public function getProducts()
{
return $this->hasMany('App\Models\Product');
}
public function getProject()
{
return $this->hasMany('App\Models\Project');
}
产品型号
use HasFactory;
protected $fillable = [
'name', 'detail', 'image', 'color', 'logo', 'user_id'
];
public function getUser()
{
return $this->belongsTo(User::class);
}
项目模型
use HasFactory;
protected $fillable = [
'name', 'detail', 'image','color','logo','user_id'
];
public function getUser(){
return $this->belongsTo(User::class);
}
我还需要帮助才能使我的模型正常工作。
【问题讨论】:
-
更改用户表 $table->id();到 $table->bigIncrements('id');
-
C:\xampp\htdocs\ContentBaseApp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471 PDOException::("SQLSTATE[HY000]: 一般错误:1005 Can' t 创建表
laravel.projects(errno: 150 "外键约束格式不正确")") -
更改后显示此错误
-
PDOException::("SQLSTATE[HY000]: 一般错误: 1005 无法创建表
laravel.projects(errno: 150 "外键约束格式不正确")") 之后更改显示此错误 -
我已经在我的系统中验证了。如果你改变 $table->id();到 $table->bigIncrements('id');在用户迁移中它工作正常。我从您的问题中复制了相同的迁移
标签: laravel eloquent laravel-8 laravel-migrations