【发布时间】:2019-10-24 18:38:46
【问题描述】:
我运行时出现此错误:
php artisan migrate:fresh
Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般 错误:外键定义中有 1 个未知列“user_id”(SQL: 创建表“用户”(“id”整数不为空主键自动增量, “名称” varchar 不为空,“电子邮件” varchar 不为空,“用户名” varchar not null, "email_verified_at" datetime null, "password" varchar not null, "remember_token" varchar null, "created_at" 日期时间 null, “updated_at”日期时间空,外键(“user_id”)引用 "users"("id") on delete cascade))
我在 youtube 上关注一个视频教程,教程的代码是这样的:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('profiles');
}
}
如果我复制并粘贴此代码,则会出现错误。所以我在stackoverflow上搜索,我找到了这个解决方案:
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->index('user_id');
});
Schema::table('profiles', function (Blueprint $table){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('profiles');
}
这是我的用户表:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('users');
}
但是今天,当我运行php artisan migrate:fresh 时,我又遇到了这个错误。
我该如何解决?
谢谢
【问题讨论】:
-
删除表并重新运行迁移!
-
您的
users表迁移在哪里 -
您应该检查您的迁移订单。 “users”表创建必须在“profiles”表创建之前运行。
-
@spyker 我正在使用用户表进行编辑
标签: sql database laravel laravel-artisan