我试图创建一个外键,但是它不起作用。
职位迁移
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string("title", 60);
$table->string("description", 200);
$table->text("content");
$table->string("photo");
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign("user_id")->references("id")
->on("users")->onDelete("cascade");
});
}
public function down()
{
Schema::dropIfExists('posts');
}
}
用户迁移
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string("name", 30);
$table->string("email")->unique();
$table->string("password");
$table->string("username")->unique();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
我正在尝试为应该通过外键与用户ID连接的帖子创建一个“ user_id”列。但是,当我进行迁移时,出现如下错误
Illuminate \ Database \ QueryException
SQLSTATE [HY000]:常规错误:1005无法创建表
mytest_db
。posts
(错误号:150“外键约束的格式不正确”)(SQL:在删除级联上,alter tableposts
添加约束posts_user_id_foreign
外键(user_id
)引用users
(id
))在W:\ domains \ mytest.uz \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Connection.php:678674▕//如果尝试运行查询时发生异常,我们将格式化错误675▕ //包含SQL绑定的消息,它将使此异常成为676▕//对开发人员有很大帮助,而不仅仅是数据库的错误。677▕catch(Exception $ e){678▕throw new QueryException(679▕$ query,$ this-> prepareBindings($ bindings),$ e680▕); 681▕}682▕
1
W:\ domains \ mytest.uz \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Connection.php:471 PDOException ::((“ SQLSTATE [HY000]:常规错误:1005无法创建表mytest_db
。posts
(errno: 150“外键约束格式不正确”)“)2
W:\ domains \ mytest.uz \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Connection.php:471 PDOStatement :: execute()
无法在尚不存在的表上定义外键。
Laravel以文件名顺序执行迁移,在迁移名称之前加上时间戳。确保CreatePostsTable
迁移是在迁移之后进行的CreateUsersTable
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句