laravel - Laravel:迁移和播种问题
问题描述
我正在尝试为数据库播种,但在运行时出现错误php artisan migrate:fresh
:
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `news` add constraint `news_author_id_foreign` foreign key (`author_id`) references `authors` (`id`) on delete cascade)
at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
665| // If an exception occurs when attempting to run a query, we'll format the error
666| // message to include the bindings with SQL, which will make this exception a
667| // lot more helpful to the developer instead of just the database's errors.
668| catch (Exception $e) {
> 669| throw new QueryException(
670| $query, $this->prepareBindings($bindings), $e
671| );
672| }
673|
1 C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
2 C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOStatement::execute()
以下是迁移文件:
Schema::create('news', function (Blueprint $table) {
$table->bigIncrements('id');
...
$table->unsignedBigInteger('author_id');
$table->foreign('author_id')
->references('id')
->on('authors')
->onDelete('cascade');
});
Schema::create('authors', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
这里是工厂文件:
$factory->define(Author::class, function (Faker $faker) {
return [
'name' => $faker->name
];
});
return [
...
'author_id' => $faker->numberBetween($min = 1, $max = 50),
];
最后,这里是种子文件:
// DatabaseSeeder
{
$this->call(AuthorsTableSeeder::class);
$this->call(NewsTableSeeder::class);
}
// NewsSeeder and AuthorSeeder
factory(App\News::class, 150)->create();
factory(App\Authors::class, 50)->create();
知道为什么我会收到此错误以及我可以做些什么来解决它吗?
谢谢。
解决方案
仅仅因为news
之前运行的迁移文件authors
只需尝试更改这两个文件的时间戳以使authors
迁移在news
迁移之前运行
推荐阅读
- kdb - 根据正数或负数更新表值
- python - 如何获取有关 python 错误的更多信息?
- c++ - 导入库问题“导入库格式存档中已识别但未处理的机器类型 (0x8664)”
- facebook - 当请求用户被禁止做的事情时,facebook api 会返回什么?
- amazon-web-services - 恢复 Etcd 法定人数
- javascript - 卡片翻转悬停并单击
- r - 从托管在外部服务器上的 Shiny 应用程序访问本地目录结构?
- python - Pyspark:使用 Zeppelin Notebook 在 Hive 中插入表的问题
- figma-api - 如何从 Figma 中的 JSON 文档中获取节点的轮换?
- python - 发送这样的ajax帖子安全吗?如果没有,如何清洗?