php - Laravel 5.4 建议通过 migrate :reset? 使用 "enable/disableForeignKeyConstraints()"

标签 php database laravel laravel-5 laravel-5.4

我的 laravel 5.4 应用程序包含具有许多关系的复杂数据库结构,因此我愿意知道使用 Schema::enableForeignKeyConstraints();Schema::disableForeignKeyConstraints( );down() 函数中。因为如果我运行命令 php artisan migrate:reset 那么就会存在关系并且不可能删除...

完整示例:

public function down()
{
     Schema::disableForeignKeyConstraints();
     Schema::drop('blog');
     Schema::enableForeignKeyConstraints();
}

如上所述,由于数据库功能,建议使用此选项?

最佳答案

通常,您会按照特殊顺序迁移数据库,这样就不会与外键发生冲突,例如 创建:

  1. 用户
  2. 权限
  3. 用户权限

当您想要回滚时,最好的方法是撤消所有操作,以便您开始

删除:

  1. 用户权限
  2. 权限
  3. 用户

一个常见的错误是这个例子:

class User extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('username')->nullable()->unique();
            $table->timestamps();
        });

        Schema::create('user_permission', function (Blueprint $table) {
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->integer('permission_id')->unsigned();
            $table->foreign('permission_id')->references('id')->on('permissions');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users'); // error will be thrown, because user_permission still exists. 
        Schema::dropIfExists('user_permission');

    }
}

当然,您可以使用 disableForeignKeyConstraints,但在我看来,这是一种肮脏的解决方案,您应该遵循迁移表的相同方式(同样的方式 = 不要禁用外键)。

关于php - Laravel 5.4 建议通过 migrate :reset? 使用 "enable/disableForeignKeyConstraints()",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44107951/

相关文章:

mysql - ACID 事务,持久性

java - 如何用java从数据库中获取所有子类别

php - Laravel 5.1 Dynamic where/orWhere

从数组循环创建的 PHP 常量

javascript - 将 Javascript 变量安全地传递给 PHP(使用 AJAX)

mysql - 两个表之间的多对多关系

php - 通过 AJAX 的 Laravel Route 调用获取错误的 URL 404(未找到)

php - Laravel Dusk - 类配置不存在

php - 不能使用 stdClass 类型的对象作为数组

php - 根据模式更改字符串