【问题标题】:How to create a self-reference relationship (foreign key) in a Laravel migration?如何在 Laravel 迁移中创建自引用关系(外键)?
【发布时间】:2016-12-07 06:22:22
【问题描述】:

我从一个基于 Laravel 5.2 的自学项目开始,我发现了我的第一个问题:迁移中的自引用。

这就是文件2016_08_02_024942_create_navigation_table.php 的样子(我已经删除了 cmets,以免帖子太长):

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateNavigationTable extends Migration
{
    public function up()
    {
        Schema::create('navigation', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id')->unsigned();
            $table->integer('position')->unsigned();
            $table->string('title');
            $table->string('slug');
            $table->string('permissions')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });
    }

    public function down()
    {
        Schema::drop('articles');
    }
}

然后因为我在这里阅读了几篇文章,例如thisthisthis 等等,所以我使用以下代码创建了另一个文件,其关系名为 2016_08_02_030158_add_parent_to_navigation_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddParentToNavigationTable extends Migration
{
    public function up()
    {
        Schema::table('navigation', function (Blueprint $table) {
            $table->foreign('parent_id')->references('id')->on('navigation')->onUpdate('cascade')->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::drop('articles');
    }
}

但是当我运行命令php artisan migrate 时出现以下错误,我不确定自己做错了什么:

[Illuminate\Database\QueryException] SQLSTATE[42S01]:基表或 视图已存在:1050 表“导航”已存在(SQL: 创建表navigation (id int unsigned not null auto_increment 主键,position int unsigned not null,title varc har(255) 不为空,slug varchar(255) 不为空,permissionsvarchar(255) 空,created_at 时间戳空,updated_at 时间戳空, deleted_attimestamp null) 默认字符集 utf8 collat​​e utf8_unicode_ci 引擎 = InnoDB)

[PDOException] SQLSTATE[42S01]:基表或视图已存在: 1050 表“导航”已存在

谁能给我一些建议?我做错了什么?我见过this package,但我不确定它是否能解决我的问题。

【问题讨论】:

  • 您是否在再次运行之前清除了数据库?
  • 另外你不需要为increments() 添加unsigned() 但默认它是无符号的(提示)
  • @xdevnull 我已经运行了命令php artisan migrate:rollback 并清除了数据库
  • 请确保它已被删除。 rollback 不足以证明,由于某些原因,```rollback`` 可能无法删除表。
  • @xdevnull 完美,我已经检查过了,你是对的,navigation 表没有被删除,因此它失败了,感谢两个提示。

标签: laravel laravel-5.2 laravel-migrations laravel-schema-builder


【解决方案1】:

SQLSTATE[42S01]:基表或视图已存在:1050 表 “导航”已经存在

表示您在数据库中有相同的表名

因此您需要验证,您的数据库中没有任何具有该名称

  • 确保没有同名的表名
  • 再次运行迁移

    php artisan migration:rollback 有时会因为各种原因无法删除表。

【讨论】:

    猜你喜欢
    • 2020-12-16
    • 2021-12-31
    • 1970-01-01
    • 2018-06-19
    • 2013-08-27
    • 1970-01-01
    • 2018-05-16
    • 2023-01-04
    相关资源
    最近更新 更多